R-来自同一数据集的多个图:相同的x值,但y值不断变化

时间:2018-09-17 11:37:35

标签: r ggplot2 dplyr data-visualization

通常我有一个数据集,需要从中创建多个图,其中x值保持不变,但y值却发生变化。
例如,下面的df代码具有1个因子变量,年份和3个度量。
我需要绘制3个图,其中唯一变化的是y的值。

library(dplyr)
library(ggplot2)
years <- c(2012,2013,2014,2015)
count <- c(20,25,28,31)
spend <- c(300,320,310,341)
prop <- c(.7,.3,.5,.8)

df <- data.frame(years,count,spend,prop)

ggplot(df,aes(x = years, y = count)) +
  geom_col()

ggplot(df,aes(x = years, y = spend)) +
  geom_col()

ggplot(df,aes(x = years, y = prop)) +
  geom_col()

这是一个非常简单的版本,我的实际图形更加精细。
到目前为止,我已经使用循环生成了多个图形,创建了一个函数,然后该函数在循环中执行,并且完成了简单的复制/粘贴操作。
还有其他更正式的方法吗?是dplyrggplot还是其他任何东西?

谢谢

1 个答案:

答案 0 :(得分:3)

melt()的数据和facet_wrap()的图怎么样?

library(reshape2)
df <-melt(df, id=c("years")) 

library(ggplot2)  
ggplot(df,aes(x = years, y =value)) +
  geom_col() + facet_wrap(~variable)

enter image description here

或者,如果您想要不同的y轴比例尺:

ggplot(df,aes(x = years, y =value)) +
  geom_col() + facet_wrap(~variable, scales = "free_y")

enter image description here