在没有条形图的图例中显示 geom_abline

Showing geom_abline in legend without bar

我想在图例中通过 geom_abline 显示添加的行,因为条形图在 x 轴标签中表示。

真尴尬,不知道我怎么忘了玩具数据。我还清理了示例,确保我 运行 是 R 和 ggplot 的最新版本(并重塑!)我忘记了它有时是如何产生影响的

最终产品是一个条形图,添加了线条(表示平均值),图例中显示了此信息,所以红色虚线表示 "County Average"。

library(ggplot2)
DataToPlot.. <- data.frame(UGB = c("EUG","SPR","COB","VEN"),
            Rate = c( 782, 798,858,902))

ggplot(DataToPlot.. ,y = Rate, x = UGB) + 
    geom_bar(aes(x=UGB,y=Rate, fill = UGB),stat="identity",show.legend =  FALSE) +
    scale_fill_brewer(palette="Set3") +
    geom_abline(aes(intercept = 777, slope = 0), colour = "red", 
                               size = 1.25, linetype="dashed",show.legend = TRUE)   

玩了一段时间后(没有我想象的那么容易)我用了这个:

library(ggplot2)

DataToPlot.. <- data.frame(UGB = c("EUG","SPR","COB","VEN"),
                           Rate = c( 782, 798,858,902))

x <- c(0.5,nrow(DataToPlot..)+0.5)
AvgLine.. <- data.frame(UGB=x,Rate=777,avg="777")

ggplot(DataToPlot.. ,y = Rate, x = UGB) + 
  geom_bar(aes(x=UGB,y=Rate, fill = UGB),stat="identity",show.legend=TRUE ) +
  scale_fill_brewer(palette="Set3") +

  geom_line(data=AvgLine..,aes(x=UGB,y=Rate,linetype=avg),
                              colour = "red", size = 1.25) +
  scale_linetype_manual(values=c("777"="dashed")) +

  # make the guide wider and specify the order
  guides(linetype=guide_legend(title="Country Average",order=1,keywidth = 3),
            color=guide_legend(title="UGB",order=2))      

请注意,我无法强迫 geom_abline 制作自己的指南。我必须创建一个数据框。该行的 x-coordinates 基本上是因子值,我调整了它们以超出图的边缘。

得到这个: