r - 正负值ggplot2的不同颜色
问题描述
我想绘制我的数据,突出显示正值和负值(分别为“firebrick”和“dodgerblue4”)并创建一个图例,其中“Upwelling”为正值,“Downwelling”为负值。我的代码现在看起来像这样:
ggplot(dados19,aes(Date,UI))+
geom_line()+
ggtitle("Upwelling Index during the period 2012-2019")+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Year") + ylab("Upwelling index")
A tibble: 10,225 x 2
UI Date
<dbl> <dttm>
37.9 2012-01-01 00:00:00
9.18 2012-01-01 06:00:00
1.18 2012-01-01 12:00:00
27.0 2012-01-01 18:00:00
-292. 2012-01-02 00:00:00
98.2 2012-01-02 06:00:00
95.9 2012-01-02 12:00:00
6.19 2012-01-02 18:00:00
-4.65 2012-01-03 00:00:00
40.1 2012-01-03 06:00:00
# ... With 10,215 more rows
最好的表示方法是使用渐变
scale_color_gradient(low = "dodgerblue4",high = "firebrick")+
情节是这样的:
我需要相同的图,但只有 2 种颜色(红色表示正值,蓝色表示负值),而不是渐变。
解决方案
给出一个可重现的例子:
dados19 <- tibble::tribble(~UI , ~Date,
37.9 , "2012-01-01 00:00:00",
9.18, "2012-01-01 06:00:00",
1.18, "2012-01-01 12:00:00",
27.0 , "2012-01-01 18:00:00",
-292. , "2012-01-02 00:00:00",
98.2 , "2012-01-02 06:00:00",
95.9 , "2012-01-02 12:00:00",
6.19, "2012-01-02 18:00:00",
-4.65, "2012-01-03 00:00:00",
40.1 , "2012-01-03 06:00:00")
dados19$Date <- lubridate::as_datetime(dados19$Date)
您可以按以下方式进行:
library(ggplot2)
ggplot(dados19, aes(Date, UI)) +
geom_line() +
geom_point(aes(colour = factor(sign(UI))), size = 3) +
scale_colour_manual(values = c("firebrick", "black", "dodgerblue4"),
breaks = c("-1", "0", "1"),
labels = c("Downwelling", "Stationary", "Upwelling")) +
labs(title = "Upwelling Index during the period 2012-2019",
x = "Year",
y = "Upwelling index",
colour = "Up/Down") +
theme(plot.title = element_text(hjust = 0.5))
我不知道你是否想要一些彩色点或条..
我添加了一条geom_points
指令来添加您想要的功能。
请注意,它colour =
定义了点的颜色。我已按照您的要求将其设置为 UI 的符号。我不得不强制它成为一个因素,以便它提供两种单独的颜色(而不是渐变)。
最后,我习惯于scale_colour_manual
设置你想要的颜色。
sign
仅返回 3 个值:-1、0、1。您没有为零场景提供颜色,因此我设置了“黑色”,但您可以更改它。您可以将labels
-1, 0, 1 替换为您想要的文本。
推荐阅读
- mongodb - 将对象的 MongoDb 中的字段更新为对象数组 - 命令行
- java - 即使在项目中检测到错误,eclipse有没有办法运行Java程序?
- c# - ASP.NET 我无法让模型将数据带回控制器。它始终为 0
- excel - VBA 的问题 - 复制模板工作表并使用输入框重命名
- python - XML到Python中的字典到DataFrame
- vba - 如何将数字日期转换为字符日期,月份名称位于表单的不同字段中?(使用权)
- qt - Qt5 Openvino opencv cmake windows
- javascript - 使用日期时间字段填充 chartjs ajax
- ios - URLImage 永远不会在 SwiftUI 的小部件应用中加载图像
- excel - Excel VBA:将每个工作表名称更改为每个工作表中的单元格 A1 值