【问题标题】:ggplot() geom_smooth() color gives me the wrong colorsggplot() geom_smooth() 颜色给了我错误的颜色
【发布时间】:2018-08-23 14:25:50
【问题描述】:

我不知道为什么我的颜色会倒退。有人可以解释一下这段代码中颜色是如何分配的吗?我正在尝试在 ggplot2 参考站点上使用示例,但我已经坚持了很长时间。代码如下:

#libraries
library(ggplot2)
library(scales)
library(reshape2)

#data
client.data <- read.csv('client.total.sorted.csv', header = TRUE, sep = ",")

#plot
ggplot(data = client.sorted) +
    geom_smooth(mapping = aes(x = Date, y = Cancelled, color = "red")) +
    geom_point(mapping = aes(x = Date, y = Cancelled, color = "red")) +
    geom_smooth(mapping = aes(x = Date, y = Active, color = "green")) +
    geom_point(mapping = aes(x = Date, y = Active, color = "green")) +
    labs(title = "activations vs cancellations", x = "Date", y = "")

这是输出:

【问题讨论】:

  • 将颜色规范移到aes()之外。但通常我们不会在 ggplot 中以这种方式指定颜色。相反,我们会将数据从宽转换为长,以便 Active 和 Canceled 是数据列中的值。 那么您可以将颜色映射到aes() 内的该变量。这是映射和设置美学之间的区别。
  • @joran 感谢您的帮助。将颜色移到审美之外就如你所说。当前数据是这样设置的: > Date Active Canceled - 你是说我应该把它融化,这样 Active 和 Canceled 就在同一列吗?我不确定那会是什么样子。
  • 是的,完全正确。您可以使用tidyr::gather() 并以列日期、组和值结束,其中组处于活动状态或已取消。然后您将只有 一个 geom_smoothgeom_point 层,并且您将 map 颜色到组。这是使用ggplot的正确方法。除特殊情况外,如果您像这样添加多个图层,则表明您没有正确排列数据。

标签: r plot ggplot2 colors


【解决方案1】:

我发现这篇文章引用了帮助我解决这个问题的传说:

Add legend to ggplot2 line plot

对我有用的解决方案是:

ggplot(data = client.sorted) +
    geom_smooth(mapping = aes(x = Date, y = Cancelled, color = "CancelledLines")) +
    geom_point(mapping = aes(x = Date, y = Cancelled, color = "CancelledPoints")) +
    geom_smooth(mapping = aes(x = Date, y = Active, color = "greenLines")) +
    geom_point(mapping = aes(x = Date, y = Active, color = "greenPoints")) +
    scale_color_manual("",
                       breaks = c("CancelledLines", "CancelledPoints", "greenLines", "greenPoints"),
                       values = c("red", "red", "green", "green")) +
    labs(title = "activations vs cancellations", x = "Date", y = "")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多