首页 > 解决方案 > ggplot中的颜色编码多个条件

问题描述

我正在尝试制作一个基于多个条件捕获数据并对其进行颜色编码的图。

在使用此代码之前,我已成功制作图表:

ggplot(data2_CY, aes(x = Date, y = AVERAGETOTALCOST)) + geom_point(color = 'blue') + geom_point(data = data2_CN, color = 'red') + 
  geom_point(data = data2_LY, color = 'cyan') + geom_point(data = data2_LN, color = 'magenta') + 
  labs(title = "Average Total Cost Trends Over Time", x = "Time", y = "Average Total Cost") + scale_x_date(breaks = seq(as.Date("2017-01-01"), as.Date("2019-07-01"), by = "6 months"), date_labels = "%b\n%Y")

问题是我使用了 4 个单独的数据框,因此我无法使用它创建图例,scale_color_manual()因为它仅使用来自一个数据框的数据。

为了解决这个问题,我将数据框组合成一个数据框,如下所示:

Date       |  CL  | TF | AVERAGETOTALCOST  
2017-01-01 |   C  |  T | 12325.120
2017-01-01 |   C  |  F | 12504.443
2017-01-01 |   L  |  T | 2050.544
2017-01-01 |   L  |  F | 3055.342
2017-02-01 |   C  |  T | 14055.543

等等...

如何使用 ggplot 对 4 个条件中的每一个进行颜色编码?有C&T、C&F、L&T、L&F。我有一些类似的东西:

ggplot(data2_CL) + geom_point(aes(x = Date, y = AVERAGETOTALCOST) color = ) + scale_color_manual(value = )

但不确定如何进行。

谢谢!

标签: rggplot2

解决方案


这可以通过连接您的CLTF列 a 并将新变量映射到coloraes 上来实现,如下所示:

data2_CL$color <- paste0(data2_CL$CL, data2_CL$TF)

library(ggplot2)

ggplot(data2_CL) + 
  geom_point(aes(x = Date, y = AVERAGETOTALCOST, color = color)) + 
  scale_color_manual(values = c(CT = "red", CF = "blue", LT = "green", LF = "purple"))


推荐阅读