简体   繁体   中英

How do I plot two variables onto one graph using ggplot2?

You can create the data set using:

 structure(list(month = structure(c(5L, 4L, 8L, 1L, 9L, 7L, 6L, 2L, 12L, 11L, 10L, 3L, 5L, 4L,8L, 1L, 9L, 7L, 6L, 2L, 12L, 11L, 10L, 3L),.Label = c("Apr", "Aug", "Dec", "Feb", "Jan", "Jul", "Jun", "Mar", "May", "Nov", "Oct", "Sep"), class = "factor"), 
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
), .Label = c("npop", "temp"), class = "factor"), value = c(220, 
180, 150, 250, 270, 300, 500, 580, 580, 1000, 380, 100, 15, 
17, 20, 24, 26, 28, 30, 31, 30, 28, 19, 16)), row.names = c(NA, -24L), class = "data.frame")

Once created I intend to plot "temp" and "npop" both with respect to the month by using ggplot2 and the code:

p<-ggplot(data=df,aes(x=factor(month,level=level_order), y=value))+xlab("Month")+ylab("value")+geom_bar(stat="identity") 

However the error I recieve is "Error in FUN(X[[i]],...) : object 'value' not found.

Is this to do with the fact that I am including a level in my argument? This is necessary because ggplot2 lists the months in alphabetical order, so I created a seperate object which is:

level_order<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

Any help is greatly appreciated!

You can plot multiple variables in the same geom_bar() plot using the fill attribute (after having converted your data in long format) in the plot aesthetics and using position = "dodge" to get the bars side by side:

df %>% 
  ggplot(aes(month, value, fill = variable)) +
  geom_bar(stat='identity', position = "dodge")

Which outputs the following plot: 在此处输入图片说明

Your variables seem to lie on pretty different scales, I would either add a secondary axis or scale the variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM