0

Good morning, my name is Thiago and I'm having a hard time building a legend on ggplot2. The data are of wood density vs planting age and the graph I'm trying to build is with the following code:

d.idade<-ggplot(data=dens, aes(x=Idade, y=Densidade))+
 geom_point(pch=1, size=1.4)+
 geom_hline(yintercept = mean(dens$Densidade), linetype=2, color="red4", show.legend = TRUE)+
 xlim(c(0,25))+
 ylim(c(250,700))+
 xlab("Age (years)")+
 ylab("Wood density (kg/m³)")+
 theme_classic()+
 theme(axis.text.x = element_text(colour = "black", family="serif", size=10))+
 theme(axis.text.y = element_text(colour = "black", family="serif", size=10))+
 theme(axis.title.x = element_text(family ="serif", size=10))+
 theme(axis.title.y = element_text(family="serif", size=10))

enter image description here

I used the geom_hline command to construct a line representing the mean of the wood density values.

However, I would like to construct a legend that indicates that this line represents the average with the line style used and that appears in bottom of the graph.

I have tried several geom_label commands and legend, but I did not succeed in any of them, since I want the symbol (color, line type) and the description (mean valeus) of the line appear on the legend.

rawr
  • 20,481
  • 4
  • 44
  • 78
  • try: `geom_hline(aes(color= "mean", yintercept = mean(cars$dist)), linetype = 2) + scale_color_manual("", values = "red4")` – missuse Mar 26 '18 at 13:13
  • 4
    Possible duplicate of [Why doesn't geom\_hline generate a legend in ggplot2?](https://stackoverflow.com/questions/32833290/why-doesnt-geom-hline-generate-a-legend-in-ggplot2) – r.bot Mar 26 '18 at 13:20
  • You'd probably be best off using `annotation_custom` instead of a legend argument – zlipp Mar 26 '18 at 14:24

0 Answers0