sparkyjump
sparkyjump

Reputation: 117

Legend Trouble in R- how to change legend text in ggplot2

I have a plot in grey with the legend inside the plot. However, the labels in the legend are wrong. If I follow advice to change the legend labels, even without changing the theme, then I'm somehow back to the default colors. There has got to be a better way. "sex" in the legend as "Method", "m" is "1" and "f" is "2" with the plot still gray, would be a huge improvement.

require(ggplot2)
counts <- c(18,17,15,20,10,20,25,13,12)
time <- c(1, 1.3, 1.1, 1, 1, 1, 1, 1.3, 1.1)
sex <- c("m","f","m","f","m","f","m","f","m")
print(myDF <- data.frame(sex, counts, time))

gTest <- ggplot(myDF, aes(counts, time, color=sex)) +
    geom_point(size = 3)+geom_smooth(method="lm", se=F) +
    ggtitle("Long-Term Gain in Speech Rate")+
    xlab("Baseline Speech Rate") +
    ylab("Mean Speech Rate Gain")

Thanks! This changes the title

gTest + scale_colour_grey(start = .3, end = .7) + guides(color=guide_legend(title="Method")) + theme_bw()+ theme(legend.position=c(.9,.9), legend.background=element_rect(fill="white", size=0.5, linetype="solid", colour ="white"))

Upvotes: 4

Views: 3237

Answers (1)

Mike H.
Mike H.

Reputation: 14360

In order to change the legend labels, you can edit your call to scale_colour_grey() to include a labels= argument. To change the legend title, you can specify this in your guides() call. This should produce the desired result:

gTest + scale_colour_grey(start = .3, end = .7,labels=c("2","1")) +
  guides(color=guide_legend(title="Method")) +
  theme_bw()+
  theme(legend.position=c(.9,.9),
        legend.background=element_rect(fill="white",
                                       size=0.5, linetype="solid", colour ="white"))

enter image description here

Upvotes: 3

Related Questions