Reputation: 354
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!
Upvotes: 1
Views: 130
Reputation: 1641
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
Upvotes: 1