【问题标题】:How can I plot a lot of columns of a data frame with ggplot with the same color?如何使用相同颜色的 ggplot 绘制数据框的许多列?
【发布时间】:2016-04-27 19:13:47
【问题描述】:

我有一个如下所示的数据框:

  Time f1            f2
  6.04 0.0030113949 -2.816807e-03
  6.05 0.0030217415 -2.830386e-03
  6.06 0.0030320970 -2.843984e-03
  6.07 0.0030424615 -2.857600e-03
  6.08 0.0030528349 -2.871233e-03
  6.09 0.0030632171 -2.884885e-03
  6.10 0.0030736081 -2.898555e-03
  6.11 0.0030840079 -2.912242e-03

我想用相同颜色的 ggplot 绘制 f1f2,用不同颜色绘制它们的平均值,所有这些都在同一个图上。

我做了什么:

 df <- melt(df ,  id.vars = 'Time', variable.name = 'f')
ggplot(df, aes(Time,value)) + geom_line(aes(colour = f))

但它用不同的颜色绘制每一列。

【问题讨论】:

  • 您尝试过什么吗?如果您显示您尝试过的代码并询问有关您卡在哪里的特定问题,则会更容易。如果你不知道从哪里开始,我建议你在谷歌上搜索一个基本的 ggplot 教程。我们在这里不仅仅是为您编写代码;我们在这里帮助回答具体问题。
  • 我做了,并编辑了我的帖子。
  • 如果你想要所有的颜色都一样,不要在aes内部指定color,但在外部:使用color = 'grey'而不是aes(colour = f)

标签: r ggplot2


【解决方案1】:

我会拍的。

install.packages('dplyr')
library(dplyr)
df <- mutate(df, f_mean = mean(f1 + f2))

ggplot(df, aes(x = Time, y = f1)) +
    geom_point(color = 'black') +
    geom_point(aes(x = Time, y = f2), color = 'black') +
    geom_point(aes(x = Time, y = f_mean), color = 'red')

您应该能够使用该代码到达您想到达的位置。另外,看看ggplot2 cheat sheet

【讨论】:

  • 那些硬编码的data$column 会在最简单的情况下破坏ggplot。您应该使用aes(),并且只指定列名。
  • 我进一步编辑以将常量颜色移到aes() 之外。最佳做法是在 aes() 内映射数据列,但在外面保留常量。对于简单的情节并没有真正的区别,但如果有方面或其他复杂情况,这可以可靠地工作。
  • 再次感谢,格雷戈尔。我一直在使用 ggplot2,这对我有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 2017-05-26
  • 2020-03-17
  • 2020-02-24
  • 1970-01-01
  • 2015-05-27
  • 2020-04-27
  • 2019-06-16
相关资源
最近更新 更多