GenesRus
GenesRus

Reputation: 1057

How can I turn on ggplot2 legend titles?

From what I understand, ggplot2 legend titles should be on by default. However, I can't seem to get mine to appear. I've tried everything I can think (see code), but it's stubbornly missing. I cloned my environment from my boss, so it's possible that it's turned off somewhere (however, my coworkers don't have this problem), but I have no clue where to look in the environment to fix this. I'm also working in RStudio in case this is a quirk there. Any suggestions/fixes are greatly appreciated. :)

set.seed(1234)
df <- data.frame(
    sex=factor(rep(c("F", "M"), each=200)),
    weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5)))
)
ggplot(df, aes(x=weight, color=sex)) +
    geom_histogram(fill="white", position="dodge", show.legend=TRUE)+
    theme(legend.position="top") +
    labs(color='NEW LEGEND TITLE') +
    theme(legend.position="top") +
    scale_color_discrete(guide = guide_legend())

Produces: Histogram of fake data with missing legend title

Edit

My boss appears to have added a custom theme in the code we source to access his myriad functions, so the solution I've come up with the help of the comments is to add this after sourcing the code:

theme_update() + theme(legend.title = element_text(colour="black", size=12))

(Many thanks to the commenters for their useful suggestions!)

Upvotes: 0

Views: 84

Answers (2)

TobiO
TobiO

Reputation: 1381

To force printing of the legend title, specify its properties:

plot+
theme(legend.title = element_text(colour="black", size=12, face="bold"))

Upvotes: 1

Skotten89
Skotten89

Reputation: 13

Try removing duplicate code (e.g. theme(legend.position=”top”) and erase scale_color_discrete which should be redundant. I think the last piece might cause trouble although it may not be the case.

On a side note, try mapping sex to the fill aesthetic and use alpha = 0.5 in geom_histogram and play around with it if you are unfamiliar with this feature.

Upvotes: 0

Related Questions