3

I want to show the added line via geom_abline in the legend since the bar chart is denoted in the x axis labels.

How embarrassing, not sure how i forgot toy data. I also cleaned up the example making sure i was running the most up to date version of R and ggplot (and reshape!) I forgot how it can make a difference sometimes

The end product is a bar chart with the added line (indicating the average) with this information showing in the legend, so a red dotted line that says "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)   
Mike Wise
  • 22,131
  • 8
  • 81
  • 104
Josh R.
  • 449
  • 2
  • 4
  • 13

1 Answers1

3

After playing around for awhile (it was not as easy as I expected) I used this:

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))      

Note I couldn't coerce geom_abline to make its own guide. I had to create a dataframe. The x-coordinates for that line are basically the factor values, and I adjusted them to reach beyond the edges of the plot.

To get this:

enter image description here

Mike Wise
  • 22,131
  • 8
  • 81
  • 104