当我们使用多个 geom_bar 时如何添加多个图例?

How to add multiple legend when we use multiple geom_bar?

这是我的数据

       time_granularity     N   V2    V3    V4
 1: 2019-03-07 06:00:00  3445  874  1560  2569
 2: 2019-03-07 06:15:00  5871 1366  2550  3920
 3: 2019-03-07 06:30:00  9790 2157  3831  5615
 4: 2019-03-07 06:45:00 13809 3182  5497  8055
 5: 2019-03-07 07:00:00 18559 4538  8400 11707
 6: 2019-03-07 07:15:00 23563 6015 11256 15620
 7: 2019-03-07 07:30:00 28251 7103 14380 19366
 8: 2019-03-07 07:45:00 30879 7282 15784 20503
 9: 2019-03-07 08:00:00 29575 6968 14208 18269
10: 2019-03-07 08:15:00 26898 5543 11185 14575

这是代码

p <- ggplot(t, aes(x=time_granularity)) + 
  geom_bar(aes(y=N), alpha = 1,stat = "identity", fill='lightblue', color='lightblue4') +
  geom_bar(aes(y=V4),  alpha = 1,stat = "identity", fill="seagreen2", color='forestgreen') +
  geom_bar(aes(y=V3),  alpha = 1,stat = "identity", fill='yellow1', color='lightyellow4') +
  geom_bar(aes(y=V2),  alpha = 1,stat = "identity", fill='pink', color='red') +
  lims(y = c(0, 32000)) +
  scale_x_datetime( 
    date_breaks = "1 hour",
    date_labels = "%H:00")+
  xlab("")  +
  ylab("Count")

我想知道如何在此 code.I 中添加图例和标题我已经尝试了几种方法,但是 none 中的 worked.It 最好在我的代码中进行更改. enter image description here

如果你想要一个图例,你必须在美学上进行映射,即将 color=...fill = ... 移动到 aes() 并使用 scale_color/fill_manual 来设置你想要的颜色.这将自动为您的绘图添加图例。实际上你有两个,一个用于颜色,一个用于填充。这两个传说可以合并为一个,通过例如给两个相同的标题。 labs。此外,您还可以通过 labs 为情节添加标题。顺便说一句:我用更简洁的 geom_col():

替换了 geom_bar(stat="identity")
library(ggplot2)

ggplot(t, aes(x=time_granularity)) + 
  geom_col(aes(y=N, fill = "N", color = "N")) +
  geom_col(aes(y=V4, fill = "V4", color = "V4")) +
  geom_col(aes(y=V3, fill = "V3", color = "V3")) +
  geom_col(aes(y=V2, fill = "V2", color = "V2")) +
  scale_fill_manual(values = c(N = "lightblue", V4 = "seagreen2", V3 = "yellow1", V2 = "pink")) +
  scale_color_manual(values = c(N = "lightblue4", V4 = "forestgreen", V3 = "lightyellow4", V2 = "red")) +
  lims(y = c(0, 32000)) +
  scale_x_datetime( 
    date_breaks = "1 hour",
    date_labels = "%H:00") +
  labs(x = NULL, y = "Count", title = "My fancy title", fill = "My fancy legend", color = "My fancy legend")

实现所需结果的第二种方法是将数据集重塑为长或整齐的数据格式,例如使用tidyr::pivot_longer 和一些使用 dplyr 的数据整理。这样做可以让你的情节只有一个 geom_col:

library(tidyr)
library(dplyr)

t %>% 
  pivot_longer(-time_granularity, names_to = "var", values_to = "value") %>% 
  mutate(var = factor(var, levels = c("N", "V4", "V3", "V2"))) %>% 
  arrange(var) %>% 
  ggplot(aes(x = time_granularity, y = value, fill = var, color = var)) +
  geom_col(position = "identity") +
  scale_fill_manual(values = c(N = "lightblue", V4 = "seagreen2", V3 = "yellow1", V2 = "pink")) +
  scale_color_manual(values = c(N = "lightblue4", V4 = "forestgreen", V3 = "lightyellow4", V2 = "red")) +
  lims(y = c(0, 32000)) +
  scale_x_datetime(
    date_breaks = "1 hour",
    date_labels = "%H:00"
  ) +
  labs(x = NULL, y = "Count", title = "My fancy title", fill = "My fancy legend")