r - 如何在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")
解决方案
如果你想要一个图例,你必须在美学上进行映射,在 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))
推荐阅读
- javascript - 如何使用 Javascript 更新按钮文本
- python - 如何使用较低的暗淡数组作为掩码创建一个 numpy 掩码数组?
- c# - 在c#中将类作为参数而不是它的对象传递
- c - 为什么我看到的每个编程教程都无缘无故地包含 sys/types?
- c# - EF Core - 检查孩子的存在
- c - 输出太多
- webpack-4 - webpack:使用 2 个入口文件时,两个文件都包含相同的 css - 有解决方法吗?
- angular - 无法读取 HTML 中未定义的属性“temp”,
- flutter - 将“多个”有状态和无状态小部件存储在一个 dart 文件中。没事吧?
- jsp - 如何在从oracle数据库获取的jsp页面中播放视频