r - 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 = )
但不确定如何进行。
谢谢!
解决方案
这可以通过连接您的CL
和TF
列 a 并将新变量映射到color
aes 上来实现,如下所示:
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"))
推荐阅读
- javascript - 带有按钮、HtmlButtons 和 LinkButtons 的 onclick/onserverclick 问题
- c - 如何找到 qsort() 的比较操作数?
- sql-server - Azure SQL 查询性能已更改
- powerbi - Running Total in Matrix Rows
- excel - 在列和工作表之间搜索可能有多个语法错误或写在句子中的字符串
- python - Ode 集成器 Python TypeError 'float' 对象不可下标
- ruby-on-rails - 使用涉及嵌套标签和命名空间的 Nokogiri 生成 XML
- matlab - vecnorm 的广义版本 - Matlab
- vb.net - 在 Windows 窗体 Vb.net 上调整面板大小
- java - 在不知道 Firebase 实时数据库中的键值的情况下检索子值