【问题标题】:Multiple Line charts in R using ggplot2 packageR中使用ggplot2包的多个折线图
【发布时间】:2018-06-27 06:56:52
【问题描述】:

这是我的数据。我想为不同的变量创建多个折线图。使用“reshape2”包中的“melt”创建长格式数据。

The current code I am using is :

ggplot(data = agg_melt_p, aes(x=Cat, y=value)) + geom_line(aes(colour=variable))

这给了我以下错误:geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

数据:

Cat <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)

variable <- c("IL_1_Flag_p", "IL_1_Flag_p", "IL_1_Flag_p", "IL_1_Flag_p", "IL_2_Flag_p", "IL_2_Flag_p", "IL_2_Flag_p","IL_2_Flag_p", "IL_3_Flag_p", "IL_3_Flag_p", "IL_3_Flag_p", "IL_3_Flag_p", "IL_4_Flag_p", "IL_4_Flag_p", "IL_4_Flag_p", "IL_4_Flag_p", "IL_5_Flag_p", "IL_5_Flag_p", "IL_5_Flag_p", "IL_5_Flag_p")

value <- c(21,17,16,210,20,17,15,189,20,17,15,188,19,17,15,188,20,17,15,194)

agg_melt_p <- data.frame(cat, variable, value)

【问题讨论】:

  • 在几何线 aes 中试试group = variable
  • 鉴于您提供的数据快照,您的代码有效

标签: r ggplot2 charts line


【解决方案1】:

您的代码(使用colour=variableScientist_jake's suggestion 来使用group = variable)都适用于我。如下,

agg_melt_p <- data.frame(cat = c(1, 2, 3, 4, 1, 2, 3, 4, 
                  1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
              variable = c("IL_1_Flag_p", "IL_1_Flag_p", "IL_1_Flag_p", "IL_1_Flag_p",
                 "IL_2_Flag_p", "IL_2_Flag_p", "IL_2_Flag_p","IL_2_Flag_p", "IL_3_Flag_p",
                 "IL_3_Flag_p", "IL_3_Flag_p", "IL_3_Flag_p", "IL_4_Flag_p", "IL_4_Flag_p",
                 "IL_4_Flag_p", "IL_4_Flag_p", "IL_5_Flag_p", "IL_5_Flag_p", "IL_5_Flag_p",
                 "IL_5_Flag_p"),
              value = c(21, 17, 16, 210, 20, 17, 15, 189, 20, 17,
                       15, 188, 19, 17, 15, 188, 20, 17, 15, 194))

# install.packages(c("ggplot2"), dependencies = TRUE)
library(ggplot2)

ggplot(data = agg_melt_p, aes(x = cat, y = value)) + 
       geom_line(aes(colour = variable))

ggplot(data = agg_melt_p, aes(x = cat, y=value)) +  
      geom_line(aes(group = variable))

【讨论】:

  • 这对我有用!谢谢 !您还可以告诉我如何缩放我正在使用的值吗?我在此折线图上附加了一个 100% 堆叠条形图,其 X 轴与 Category 相同。
  • 很高兴它对您有用。如有任何新问题,请提出新问题
猜你喜欢
  • 2022-11-20
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多