【问题标题】:R - multiple plots from same data-set: same x-value but changing y-valueR - 来自同一数据集的多个图:相同的 x 值但改变 y 值
【发布时间】:2018-09-17 11:37:34
【问题描述】:

我经常有一个数据集,我需要从中制作多个图表,其中 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】:

    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)
    

    或者,如果您想要不同的 y 轴刻度:

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

    【讨论】:

    • 哇,真快。第二个正是我想要的。我经常使用gather()facet_wrap,但没想到会这样使用。
    • 是的,我认为您也可以使用gather(),但我更喜欢melt(),因为我已经使用过很多次了。
    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多