1

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!

5
  • 2
    Your code runs as is for me Commented Feb 4, 2020 at 13:56
  • Are you sure you're using the right dataset in reality? Seems that there's no value column, or it has a different name (capital "V"? something else?) Commented Feb 4, 2020 at 13:56
  • 1
    Your code works for me. Commented Feb 4, 2020 at 13:58
  • ...also the code as it is plots the aggregated counts and not a split between npop and temp. Commented Feb 4, 2020 at 13:59
  • I've figured it out, my argument for data was "df" for my previous plot and not "df2" Commented Feb 4, 2020 at 14:09

1 Answer 1

1

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: enter image description here

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.