Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you change the proportions of the ggplot2 graph from square to rectangle?

I'm using geom_segment to plot a timeline of activity. It's all on the same line, and since I want to present it together with other graphs, I'd much rather make the y axis much smaller. It seems that the size of the gray graph area in ggplot2 is always square though, whether I scale it larger or smaller. Is there a way to say that I want x=500 y=50 or something like that?

df2 <- structure(list(Activities =
                      structure(c(2L, 1L, 2L, 1L, 2L, 3L, 1L, 2L, 2L, 2L, 2L, 5L,
                                  4L, 3L, 2L, 2L), 
                                .Label = c("authoring", "hacking", "learning", 
                                           "surfing", "tasks"), 
                                class = "factor"), 
                      Start = c(14895L, 15005L, 16066L, 16226L, 16387L, 16394L,
                                27030L,27532L, 27600L, 27687L, 28660L, 28713L, 
                                29154L, 30264L, 30345L, 32245L), 
                      End = c(15005L, 16066L, 16226L, 16387L,16394L, 16509L, 
                              27491L, 27591L, 27628L, 28450L, 28704L, 29109L, 
                              30250L, 30345L, 31235L, 33794L)),
                 .Names = c("Activities", "Start", "End"), 
                 class = "data.frame", row.names = c(NA, -16L))
a <- 0:23

Here my plot:

ggplot(df2, aes(colour=Activities)) + 
  geom_segment(aes(x=Start, xend=End, y=0, yend=0), size=10) +
  scale_x_continuous(breaks=a * 60 * 60, labels=a) +
  xlab("Time") + ylab("") + 
  scale_y_continuous(breaks=NULL, limits=c(-.1, .1))

Sample timeline chart

like image 245
Stian Håklev Avatar asked Mar 18 '13 09:03

Stian Håklev


1 Answers

To fix the ratio on the x and y-axis to some value (e.g. 1, or 0.2), you can use coord_fixed():

g + coord_fixed(ratio = 0.2)

where g is your original plot. You have to play around a bit to get what you need. In addition, like @Andrie said, you can also fix the canvas size, e.g. using ggsave:

print(g)
ggsave("/tmp/plt.png", width = 16, height = 9, dpi = 120)

I'd try out both, or maybe combine them. See also this earlier post.

like image 105
Paul Hiemstra Avatar answered Oct 20 '22 01:10

Paul Hiemstra