r - ggplot2 manual legend inside a plot -


when run below code, density plot , histogram created. i've added 2 vertical line show mean , median. want display legend ("mean" dotted red , "median" green color) @ top-right corner of plot. can run code df available in r-studio.

ggplot(usarrests,aes(x=murder)) +    geom_histogram(aes(y=..density..),binwidth=.5,col="black",fill="white") +   geom_density(alpha=.2,fill="coral") +   geom_vline(aes(xintercept=mean(murder,na.rm=t)),color="red",linetype="dashed",size=1) +   geom_vline(aes(xintercept=median(murder,na.rm=t)),color="green",size=1)  

my question shall use theme() or else display legend in plot?

you're better off creating additional data.frame of summary statistics , adding plot instead of trying fiddle around manually creating each legend element. legend position can adjusted theme(legend.position = c())

library("ggplot2") library("reshape2") library("dplyr")  # summary data.frame summary_df <- usarrests %>%                summarise(mean = mean(murder), median = median(murder)) %>%                melt(variable.name="statistic")  # specifying colors , linetypes legend since wanted map both color , linetype # same variable.  summary_cols <- c("mean" = "red", "median" = "green") summary_linetypes <- c("mean" = 2, "median" = 1)   ggplot(usarrests,aes(x=murder)) +        geom_histogram(aes(y=..density..),binwidth=.5,col="black",fill="white") +   geom_density(alpha=.2,fill="coral") +   geom_vline(data = summary_df, aes(xintercept = value, color = statistic,               lty = statistic)) +   scale_color_manual(values = summary_cols) +   scale_linetype_manual(values = summary_linetypes) +   theme(legend.position = c(0.85,0.85)) 

giving

figure_with_legend


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -