0

Is there a way to set a width for a ggplot?

I am trying to combine three timeplots in one column. Because of y-axis values, plots have different width (two plots have axis values within range (-20 , 50), one (18 000, 25 000) - which makes plot thiner). I want to make all plots exactly the same width.

plot1<-ggplot(DATA1, aes(x=Date,y=Load))+
  geom_line()+
  ylab("Load [MWh]") +
  scale_x_date(labels = date_format("%m/%y"),breaks = date_breaks("months"))+
  theme_minimal()+
  theme(panel.background=element_rect(fill = "white") )
plot2<-ggplot(DATA1, aes(x=Date,y=Temperature))+
  geom_line()+
  ylab("Temperature [C]") +
  scale_x_date(labels = date_format("%m/%y"),breaks = date_breaks("months"))+
  theme_minimal()+
  theme(panel.background=element_rect(fill = "white") )
plot3<-ggplot(DATA1, aes(x=Date,y=WindSpeed))+
  geom_line()+
  ylab("Wind Speed [km/h]") +
  scale_x_date(labels = date_format("%m/%y"),breaks = date_breaks("months"))+
  theme_minimal()+
  theme(panel.background=element_rect(fill = "white") )
grid.arrange(plot1, plot2, plot3, nrow=3)

Combined plot looks like this: enter image description here

Uwe
  • 41,420
  • 11
  • 90
  • 134
ppi0trek
  • 117
  • 1
  • 1
  • 11

1 Answers1

1

You can simply use facetting for this. First you have to do some data munging:

library(tidyr)

new_data = gather(DATA1, variable, value, Load, Temperature, WindSpeed) 

this gathers all the data in Load, Temperature and Windspeed into one big column (value). In addition, an extra column is created (variable) which specifies which value in the vector belongs to which variable.

After that you can plot the data:

ggplot(new_data) + geom_line(aes(x = Date, y = value)) + 
   facet_wrap(~ variable, scales = 'free_y', ncol = 1)

Now ggplot2 will take care of all the heavy lifting.

ps If you make you question reproducible, I can make my answer reproducible.

Community
  • 1
  • 1
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • Thank you very much! This is exactly what I was looking for :) By making my question reproducible did you mean adding my data set? – ppi0trek Dec 04 '16 at 14:05
  • You should be aware that the method in this answer does not take into account that the variables have different units. You'll have to individually set the y-axis labels to incorporate the difference in units using 'annotate' – Jake Kaupp Dec 04 '16 at 14:32
  • @JakeKaupp, thanks I used 'gsub' to change the variable name for one with unit in it. (new_data$variable <- gsub("Load", "Load MWh",new_data$variable) It worked fine :) – ppi0trek Dec 04 '16 at 15:07
  • Great, just as long as you're aware! – Jake Kaupp Dec 04 '16 at 15:10
  • @ppi0trek adding data indeed. – Paul Hiemstra Dec 04 '16 at 16:36