首页 > 解决方案 > 正负值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 种颜色(红色表示正值,蓝色表示负值),而不是渐变。

标签: rggplot2colors

解决方案


给出一个可重现的例子:

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 替换为您想要的文本。


推荐阅读