【问题标题】:Plot using ggplot2 [duplicate]使用 ggplot2 绘图 [重复]
【发布时间】:2016-12-04 08:56:36
【问题描述】:

下面是我的数据集,我想随着时间的推移绘制变量 stateso7casdf

year    states  o7  cas df
1989     151    117 35  16
1990     150    158 27  12
1991     150    194 43  12
1992     150    173 38  9
1993     151    169 35  14
1994     153    169 23  9
1995     153    158 22  8
1996     153    157 18  6
1997     153    214 18  11
1998     154    186 17  5
1999     154    222 16  7
2000     155    210 20  4
2001     154    210 19  2
2002     155    231 17  2
2003     155    268 18  1
2004     155    236 16  3
2005     155    263 19  1
2006     155    238 17  5
2007     155    284 16  3
2008     155    318 20  4
2009     155    295 18  5
2010     155    330 20  4
2011     155    312 16  3

我使用ggplot2 包来做到这一点

ggplot(dat, aes(year, o7)) +
  geom_line()

但是,我未能在同一个图中绘制其他变量。

  • 如何绘制数据中的其他变量?以及如何分配它们 新标签(在 ggplot 中)?

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    当您想在同一个 ggplot 中绘制多个列时,强烈建议使用 reshape2 包中的 melt 函数。

    # df = your example
    require(reshape2)
    df_melt = melt(df, id = "year")
    
    ggplot(df_melt, aes(x = year, y = value, color = variable)) + geom_point()
    

    正如@Nathan Day 所提到的,列的范围有很大不同,使用facet_wrap 是可能的:

    ggplot(df_melt, aes(x = year, y = value, color = variable)) + geom_point() + 
    facet_wrap(~variable, scales = "free")
    

    【讨论】:

    • 谢谢,看起来很棒。一件事:如何切换到不同形状的线条而不是不同颜色的点——我是色盲..
    • 切换到线条很简单 geom_lines(),但是如何让它们变成不同的形状呢?
    • 如果您使用geom_line 而不是geom_point,则可以在ggplot 对象的aes 内添加linetype = variable。在aes 中使用shape = variable,然后使用geom_point 将修改点的形状。
    【解决方案2】:

    ggplot 以图形层为基础。如果您想包含多个针对time 绘制的变量,则每个变量都需要一个唯一的层:

     ggplot(dat, aes(x = year, y = o7)) +
     geom_line() +
     geom_line(aes(y = cas)) +
     geom_line(aes(y = df))
    

    请记住,ggplot 函数中的所有层(即geom_line)都试图继承ggplot(aes(...)) 设置的aes(...)。此行为由参数inherit.aes = 控制,默认情况下设置为TRUE

    因为您的列看起来有很大不同的范围,您最好使用另一个选项,例如 aes(colour = ?, shape = ?) 来回映射 casdf。可以玩的东西以获得最大的视觉效果。

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      相关资源
      最近更新 更多