首页 > 解决方案 > 如何在ggplot中显示标签

问题描述

这可能是 ggplot 被问到最多的问题之一,但我没有找到适合我的答案。似乎无论我做什么,颜色标签都不会出现在我的图表上。

(我也找不到 ggplot 的所有元素的描述,我的一个问题是我不知道它叫什么。)

图像

数据

veloaua$CantonCode,veloaua$time
BE,21:00
SG,12:00
JU,15:00
SO,9:00
ZH,7:00
ZG,8:00
BE,13:00
BE,13:00
AG,18:00
ZH,15:00
BS,16:00
BS,8:00
BS,13:00
BS,14:00
BS,10:00
BS,17:00
BS,14:00
BS,12:00
BS,11:00
BS,18:00

到目前为止我写的。

ggplot(data = veloaua[veloaua$CantonCode == "BS",], aes(x = as.POSIXct(time,format="%H:%M"), 
                                                                    y = (..count..)/sum(..count..)), , colour = "blue") +
  geom_histogram(bins = 24,
                 fill= "blue", 
                 alpha=0.3,
                 colour = "black") +
  #Die Daten für die gesamte Schweiz lege ich drüber
  geom_histogram(data = veloaua, 
                 aes(x = as.POSIXct(veloaua$time,format="%H:%M"), y = (..count..)/sum(..count..), colour = "grey"),
                 bins = 24,
                 fill= "grey", 
                 alpha=0.3,
                 colour="#303030",
                 linetype="dashed") +
  scale_colour_manual("", 
                      breaks = c("cba", "abc"),
                      values = c("red", "green"))+
  #scale_y_continuous(labels = scales::percent) +
  #labs(x ="Zeitpunkt", y ="Anteil",  colour = "kanton")+
  ggtitle("Zu dieser Uhrzeit gab es die meisten Unfälle")

标签: rggplot2tidyverse

解决方案


如果你想要一个图例,你必须在美学上进行映射,在 aes() 中移动fill="blue"(和"grey")。请注意,“蓝色”只是一个标签或占位符。要为此标签设置或分配颜色,请使用scale_fill_manual. 除了每个标签的颜色之外,您还可以通过以下labels参数为图例分配一个漂亮的标签scale_fill_manual

library(ggplot2)

ggplot(data = veloaua[veloaua$CantonCode == "BS", ], aes(
  x = as.POSIXct(time, format = "%H:%M"),
  y = (..count..) / sum(..count..)
)) +
  geom_histogram(aes(fill = "blue"),
    bins = 24,
    alpha = 0.3,
    colour = "black"
  ) +
  geom_histogram(
    data = veloaua,
    aes(x = as.POSIXct(veloaua$time, format = "%H:%M"), y = (..count..) / sum(..count..), fill = "grey"),
    bins = 24,
    alpha = 0.3,
    colour = "#303030",
    linetype = "dashed"
  ) +
  scale_fill_manual(
    values = c(blue = "blue", grey = "grey"),
    labels = c(blue = "blue label", grey = "grey label")
  ) +
  ggtitle("Zu dieser Uhrzeit gab es die meisten Unfälle")
#> Warning: Use of `veloaua$time` is discouraged. Use `time` instead.

数据

veloaua <- structure(list(CantonCode = c(
  "BE", "SG", "JU", "SO", "ZH", "ZG",
  "BE", "BE", "AG", "ZH", "BS", "BS", "BS", "BS", "BS", "BS", "BS",
  "BS", "BS", "BS"
), time = c(
  "21:00", "12:00", "15:00", "9:00",
  "7:00", "8:00", "13:00", "13:00", "18:00", "15:00", "16:00",
  "8:00", "13:00", "14:00", "10:00", "17:00", "14:00", "12:00",
  "11:00", "18:00"
)), class = "data.frame", row.names = c(NA, -20L))

推荐阅读