为手动添加的行添加一个条目到图例 [英] Add an entry to the legend for a manually added line
问题描述
我有一个用ggplot(ggplot + geom_bar)创建的直方图,并且像这样添加了一行:
+ geom_hline(aes(yintercept = 0.05),linetype ='dashed')
我想添加一个进入图例,这将表明虚线是期望的值。
虽然在Stack Overflow上有类似的问题,但我找不到答案需要...
任何想法如何做到这一点?
>在ggplot问题的情况下做出可重复的例子非常方便,下次你应该这样做。答案如下:
pre $ g $ p $ ggplot(diamonds,aes(clarity,fill = cut))+ geom_bar(position =dodge )+
#线型必须是aes; show_guide = TRUE很重要
geom_hline(aes(yintercept = 1500,linetype =Expected value),
show_guide = TRUE)+
#2表示虚线
scale_linetype_manual(Title ,values = 2)+
#修复了一些问题,尝试linetype = 1,另一个图例将被破坏
guides(fill = guide_legend(override.aes = list(linetype = 0)))
I have a histogram created with ggplot (ggplot + geom_bar) and I added a line to it like so:
+ geom_hline(aes(yintercept = 0.05),linetype='dashed')
I would like to add an entry to the legend which will indicate that the dashed line is the expected value.
Although there are similar questions on Stack Overflow, I couldn't find the answer to what I need...
Any idea how to do it?
It is quite convenient to make reproducible examples in case of ggplot questions, you should do that next time. Here is the answer:
ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar(position = "dodge") +
# linetype has to be aes; show_guide = TRUE is important
geom_hline(aes(yintercept = 1500, linetype = "Expected value"),
show_guide = TRUE) +
# 2 means dashed
scale_linetype_manual("Title", values = 2) +
# This fixes some problems, try linetype = 1 and another legend will be ruined
guides(fill = guide_legend(override.aes = list(linetype = 0)))
这篇关于为手动添加的行添加一个条目到图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!