R - 来自相同数据集的多个图:相同的x值但改变y值

问题描述 投票:0回答:1

我经常有一个数据集,我需要从中制作多个图形,其中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或其他任何东西?

谢谢

r ggplot2 dplyr data-visualization
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.