ggplot with geom_point 不显示 colorbar

问题描述 投票:0回答:1

我用 ggplot2 管理了一个线点图,其中点显示强度(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))

我试图在主题参数中添加“legend.position”,正如我在另一个问题中发现的那样

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

或者在 AES 参数中使用“填充”参数,在其他问题中也是如此

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
r ggplot2 colorbar geom-point
1个回答
0
投票

您需要映射

color
美学来改变点的颜色,而不是
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))

© www.soinside.com 2019 - 2024. All rights reserved.