【问题标题】:R - discrete colours for continuous data in ggplotR - ggplot中连续数据的离散颜色
【发布时间】:2015-08-07 15:18:27
【问题描述】:

我正在尝试绘制一些时间连续的数据。我应用了一个简单的算法,为数据的每一行分配一个离散数字 (state)。它看起来像这样。

time   flow    pre    state
0.0    0.0     3      1
0.2    0.01    4      1
0.4    0.10    10     2
0.6   -0.11    -2     0      # Set as NA in the example below

现在,我想绘制实例流(使用ggplot)并让state 确定颜色。问题是,如果我这样做了

ggplot(data) +
  geom_line(aes(x = time, y = flow, color = state))

该图的颜色对比度太小,无法轻松区分state。但是如果我这样做了

ggplot(data) +
  geom_line(aes(x = time, y = flow, color = factor(state))) +
  scale_color_manual(values = c("red", "green", "blue"))

它分割线,它们显示为三个不同的线。我想要的是使用连续比例,但添加一种或几种中间颜色进行对比。目前的解决方案是这样的

ggplot(data = alg1) +
  geom_line(aes(x = time, y = flow, colour = state)) +
  scale_color_gradient(low = "#0000FF", high = "#FF0000",
                       na.value = "#00FF00", guide = "legend")

但这 1) 仅适用于三种状态,其中一种必须为 NA,2) 从图例中排除一​​种状态 (NA),以及 3) 在图例中显示未使用的值。

当前代码生成的图像:

【问题讨论】:

  • 使用geom_line(aes(group = 1, ... 来避免将color 映射到的变量的每一级只写一行。此外,请确保提供可以为您提供所需输出的示例数据如果您有正确的代码。 IE。对于“state = 2”,您需要(至少)多一分。此外,您的scale_color_manual 似乎对应于三个“状态”。
  • 使用aes(x = time, y = flow, color = factor(state), group = 1) 防止在将state 转换为因子时绘制单独的线。请参阅?aes_group_order 了解有关团体美学如何运作的更多信息。
  • 这里对group的使用进行了很好的描述:kohske.wordpress.com/2010/12/27/faq-geom_line-doesnt-draw-lines
  • 感谢大家的意见!让我的电脑在工作,所以我要到星期一才能验证,但这看起来确实是我需要的!

标签: r ggplot2


【解决方案1】:

在 cmets 中回答:

通过aes(x = time, y = flow, color = factor(state), group = 1) 分组可防止在将状态转换为因子时绘制单独的线。

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2017-01-28
    相关资源
    最近更新 更多