我有以下数据集:
incidents.pct <- data.frame(
measure=c("Total Events (%)", "Security Events (%)", "Filtered (%)", "Tickets (%)"),
high=c(100,100,100,100),
mean=c(45,40,50,30),
low=c(25,20,10,5),
target=c(55,40,45,35),
value=c(50,45,60,25))
Run Code Online (Sandbox Code Playgroud)
我用它来创建以下"子弹般的"图形.
g <- ggplot(incidents.pct) +
geom_bar(aes(measure, high), fill="goldenrod2", stat="identity", width=0.5, alpha=0.2) +
geom_bar(aes(measure, mean), fill="goldenrod3", stat="identity", width=0.5, alpha=0.2) +
geom_bar(aes(measure, low), fill="goldenrod4", stat="identity", width=0.5, alpha=0.2) +
geom_point(aes(measure, target), colour="red", size=2.5)
Run Code Online (Sandbox Code Playgroud)
这有效,但我希望包含一个解释颜色的自定义图例.所以只是一个带有"低","中等","价值"等的颜色标志......
有关如何包含此内容的任何建议吗?
在ggplot中,如果它在里面,则会自动生成一个美学选项的图例aes()
.因此,以下解决方法scale_fill_manual()
将为您提供一个图例:
ggplot(incidents.pct) +
geom_col(aes(measure, high, fill = "high"), width=0.5, alpha=0.2) +
geom_col(aes(measure, mean, fill = "mean"), width=0.5, alpha=0.2) +
geom_col(aes(measure, low, fill = "low"), width=0.5, alpha=0.2) +
geom_point(aes(measure, target), colour="red", size=2.5) +
scale_fill_manual(name = "Legend",
values = c("high" = "goldenrod2",
"mean" = "goldenrod3",
"low" = "goldenrod4"),
breaks = c("high", "mean", "low"))
Run Code Online (Sandbox Code Playgroud)
(顺便提一下,geom_col()
相当于geom_bar(stat = "identity")
,看起来更整洁.
我会警告不要使用重叠条形的低alpha值,因为图例的颜色与图形的颜色不完全匹配.选择三种较浅的色调会更清晰,并将alpha保留为1.