DJMJ
DJMJ

Reputation: 107

ggplot sequence patterns

I am trying to plot a sequence of coloured small squares representing different types of activities. For example, in the following data frame, type represents the type of activity and count represent how many of those activities ocurred before a "different typed" one took place.

df3 <- data.frame(type=c(1,6,4,6,1,4,1,4,1,1,1,1,6,6,1,1,3,1,4,1,4,6,4,6,4,4,6,4,6,4),
      count=c(6,1,1,1,2,1,6,3,1,6,8,10,3,1,2,2,1,2,1,1,1,1,1,1,3,3,1,17,1,12) )

In ggplot by now I am not using count. I am just giving consecutive numbers as xvalues and 1 as yvalues. However it gives me something like ggplot Image This is the code I used, note that for y I always use 1 and for x i use just consecutive numbers:

 ggplot(df3,aes(x=1:nrow(df3),y=rep(1,30))) + geom_bar(stat="identity",aes(color=as.factor(type)))

I would like to get small squares with the width=df3$count.

Do you have any suggestions? Thanks in advance

Upvotes: 2

Views: 865

Answers (1)

bdemarest
bdemarest

Reputation: 14667

I am not entirely clear on what you need, but I offer one possible way to plot your data. I have used geom_rect() to draw rectangles of width equal to your count column. The rectangles are plotted in the same order as the rows of your data.

df3 <- data.frame(type=c(1,6,4,6,1,4,1,4,1,1,1,1,6,6,1,
                         1,3,1,4,1,4,6,4,6,4,4,6,4,6,4),
                 count=c(6,1,1,1,2,1,6,3,1,6,8,10,3,1,2,
                         2,1,2,1,1,1,1,1,1,3,3,1,17,1,12))

library(ggplot2)

df3$type <- factor(df3$type)
df3$ymin <- 0
df3$ymax <- 1
df3$xmax <- cumsum(df3$count)
df3$xmin <- c(0, head(df3$xmax, n=-1))

plot_1 <- ggplot(df3, 
              aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, fill=type)) +
          geom_rect(colour="grey40", size=0.5)

png("plot_1.png", height=200, width=800)
print(plot_1)
dev.off()

enter image description here

Upvotes: 2

Related Questions