如何使用ggplot2将两个变量绘制到一张图上?

时间:2020-02-04 13:49:35

标签: r ggplot2

您可以使用以下方法创建数据集:

 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")

创建后,我打算通过使用ggplot2和以下代码分别针对月份绘制“ temp”和“ npop”:

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

但是我收到的错误是“ FUN(X [[i]],...)中的错误:找不到对象'值'。

这与我在论点中包括一个级别有关吗?这是必需的,因为ggplot2会按字母顺序列出月份,因此我创建了一个单独的对象,即:

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

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以在情节美学中使用geom_bar()属性(在以长格式转换数据之后)在同一fill情节中绘制多个变量,并使用position = "dodge"获取条形图并排:

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

输出以下图: enter image description here

您的变量似乎位于完全不同的比例上,我可以添加辅助轴或缩放变量