【问题标题】:ggplot geom_line(): problems colouring the lines by a factor variableggplot geom_line():通过因子变量为线条着色的问题
【发布时间】:2018-02-15 10:17:07
【问题描述】:

我正在尝试使用 ggplot 在 y 轴上绘制粒子数 dN 与在 x 轴上的直径 Dp。多年来,我每月都有平均值。

我的数据是以长格式准备的。 monthyearmonth_year 是因子,DpdN 是数字。我有几年和几个直径(Dp)。

 month year   Dp        dN month_year
    1 2006 3.16 4045.1261   1 / 2006
    2 2006 3.16 4447.6436   2 / 2006
    3 2006 3.16 6436.9364   3 / 2006
    4 2006 3.16 5632.1306   4 / 2006
    5 2006 3.16 4840.1949   5 / 2006
    6 2006 3.16 1480.3604   6 / 2006
    7 2006 3.16  928.6990   7 / 2006
    8 2006 3.16 1258.5296   8 / 2006
    9 2006 3.16  725.8546   9 / 2006
   10 2006 3.16  767.1681  10 / 2006
   11 2006 3.16  647.2605  11 / 2006
   12 2006 3.16  449.9188  12 / 2006
    1 2007 3.16  647.4428   1 / 2007
    2 2007 3.16  682.0582   2 / 2007
    3 2007 3.16  614.0303   3 / 2007`

我首先用month_yearvariable 为每一行着色:

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour = month_year), size=0.5)+
  theme(legend.position = "none")+
  scale_x_log10()

我得到了这个:

每条线对应一个月,月份大致用相同的颜色着色(我的意思是,绿色大致对应于所有年份的“一月”等)。传说太长了,我就不剧透了。

现在,我想获得完全相同的图表,但每个月使用相同的颜色(并包括图例)。

这是我尝试过的:

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour = month), size = 0.5)+
  scale_x_log10()

但我得到了这个:

我也试过了

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN), colour = month, size = 0.5)+
  scale_x_log10()

但我收到以下错误:“rep(value[[k]], length.out = n) 中的错误: 尝试复制“闭包”类型的对象”

谁能帮我解决这个问题?我需要以不同的方式排列数据吗?

谢谢

【问题讨论】:

  • 你试过geom_line(aes(Dp, dN, colour=month, group=month_year)吗?
  • Dp 变量是否总是 3.16?
  • 感谢@drmariod,它成功了!
  • @Antonis,不,变量 Dp 从 3.16 变为 700...我刚刚发布了我的数据集的第一行。
  • 如果您在下面接受我的回答,我将不胜感激。 :-)

标签: r ggplot2 grouping


【解决方案1】:

因此解决方案应该是为实际上是您的month_year 但颜色为month 的行定义组。

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour=month, group=month_year), size=0.5)+
  theme(legend.position="none")+
  scale_x_log10()

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多