R语言 带有geom_point的ggplot不显示颜色条

ttvkxqim  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(153)

我已经用ggplot 2管理了一个线点图,其中点显示强度(y轴)和日期(x轴),并且还显示了另一个感兴趣的值的颜色。
然而,我不能设法使它显示颜色栏的值。它只是从来没有显示。

ggplot(
  DF, aes(x = mydate, y = myintensity)) +
  geom_point(size = 3, color = as.character(mycolormap[as.numeric(myhours)])) +
  geom_line(linetype = "dashed", color = "red") +
  geom_vline(xintercept = as.numeric(as.Date("2019-12-27")), color = "cyan", linetype = "solid")+ 
  geom_vline(xintercept = as.numeric(as.Date("2021-03-12")), color = "green", linetype = "solid")+ 
  scale_x_date(date_labels = "%b %Y", date_breaks = "1 month") +
  labs(x = "Date", y = "Intensity", title = "Chronology") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

我试着在主题论证中加入“图例。位置”,就像我在这里的另一个问题中发现的那样

theme(axis.text.x = element_text(angle = 90, vjust = 0.5,
      legend.position = "top", legend.key.width = unit(2.5, "cm"))

或在AES参数中使用“fill”参数,如在另一个问题中

ggplot(DF, aes(x = mydate, y = myintensity, 
       fill = as.character(mycolormap[as.numeric(myhours)]))

没有工作。我如何显示颜色栏?谢谢!

dput(head(ExampleDF))
structure(list(Date = c("2019-05-26", "2019-05-27", "2019-09-19", 
"2019-09-20", "2019-12-25", "2019-12-25"), Time = c("11:11:00", 
"04:00:00", "07:00:00", "11:11:00", "04:00:00", "11:00:00"), 
    DateTime = c("2019-05-26 11:11:00", "2019-05-27 04:00:00", 
    "2019-09-19 07:00:00", "2019-09-20 11:11:00", "2019-12-25 04:00:00", 
    "2019-12-25 11:00:00"), TimeOnly = c("1905-06-21 11:11:00", 
    "1905-06-21 04:00:00", "1905-06-21 07:00:00", "1905-06-21 11:11:00", 
    "1905-06-21 04:00:00", "1905-06-21 11:00:00"), Intensity = c(5L, 
    10L, 10L, 10L, 7L, 10L), Comments = c("Feeling ill for days", 
    "", "", "", "", ""), SeriesComments = c("This section covers some ", 
    "", "", "", "", "")), row.names = c(NA, 6L), class = "data.frame")

library(lubridate)
library(viridis)

mydate <- as.Date(DF$DateTime,format = "%Y-%m-%d %H:%M:%S")
mytime <- lubridate::as_datetime(DF$DateTime)
myhours <- lubridate::hour(DF$DateTime)
myintensity <- as.numeric(DF$Intensity)
mycolormap<-magma(24) #creates a color for each hour
rdlzhqv9

rdlzhqv91#

您需要Mapcolor美学来更改点的颜色,而不是fill美学。如果您想要岩浆颜色,请在图中使用scale_color_viridis_c

ggplot(ExampleDF, aes(as.Date(Date), Intensity, 
                      color = lubridate::hour(DateTime))) +
  geom_point(size = 3) +
  scale_color_viridis_c('Hour', option = 'magma') +
  geom_line(linetype = "dashed", color = "red") +
  geom_vline(xintercept = as.numeric(as.Date("2019-12-27")), color = "cyan", 
             linetype = "solid")+ 
  geom_vline(xintercept = as.numeric(as.Date("2021-03-12")), color = "green", 
             linetype = "solid")+ 
  scale_x_date(date_labels = "%b %Y", date_breaks = "1 month") +
  labs(x = "Date", y = "Intensity", title = "Chronology") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

相关问题