# [R] Stacked bar plot of frequency vs time

Marc Schwartz marc_schwartz at me.com
Mon Jul 11 17:49:42 CEST 2011

```On Jul 11, 2011, at 9:36 AM, marcel wrote:

> Hi All,
> New to R, but committed. I looked in a number of places but can't figure out
> my current problem. I have date of the type:
>
> Time Type1  Type2  Type3
> 1        .50       .25     .25
> 4        .55       .25     .20
> 5        .65       .20     .15
> etc
>
> which describe the frequency of types 1, 2 and 3 (adding up to 100%) over
> time. I would like to create a stacked bar chart showing these frequencies,
> each bar of height = 1, subsections of bars proportional to the frequency,
> and each bar located at the correct X (time) position. One difficulty is
> that the desired spacing of bar locations on the x-axis is irregular. Is
> this possible in R?
>
> Many thanks,
> Marcel

In addition to Rich's solution using lattice, here is one possible approach using base graphics:

> dput(DF)
structure(list(Time = c(1L, 4L, 5L), Type1 = c(0.5, 0.55, 0.65
), Type2 = c(0.25, 0.25, 0.2), Type3 = c(0.25, 0.2, 0.15)), .Names = c("Time",
"Type1", "Type2", "Type3"), class = "data.frame", row.names = c(NA,
-3L))

> DF
Time Type1 Type2 Type3
1    1  0.50  0.25  0.25
2    4  0.55  0.25  0.20
3    5  0.65  0.20  0.15

# Create a newdata frame with a column with the full Time sequence
TimeFill <- data.frame(Time = with(DF, min(Time):max(Time)))

> TimeFill
Time
1    1
2    2
3    3
4    4
5    5

# merge the full sequence and the original DF together. See ?merge
DF2 <- merge(DF, TimeFill, all = TRUE)

> DF2
Time Type1 Type2 Type3
1    1  0.50  0.25  0.25
2    2    NA    NA    NA
3    3    NA    NA    NA
4    4  0.55  0.25  0.20
5    5  0.65  0.20  0.15

# Now transpose the columns in DF to the matrix required for the plot
barplot(t(DF2[, -1]), names.arg = DF2\$Time)

HTH,

Marc Schwartz

```