2

I have the following data frame:

 df = data.frame(
  x = c(1:10, 1:10),
  y = 1:20,
  group = rep(c('male', 'female'), each = 10))

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth()

As you can see, the text legend (male, female) appears right to the key legend (the blue and red horizontal bar). For language reasons I want the opposite: the key legend should be at the right of the text legend. I only found a solution to align the text to the left or the right, but not to put the key before or after the text. (See here Align legend text in ggplot)

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth() +
  theme(
    legend.text.align = 1)

Any idea?

Rtist
  • 3,825
  • 2
  • 31
  • 40
  • sorry, do you want the text `male` next to the male line and female next to the female line? – amrrs Jan 08 '20 at 13:39
  • I want the text 'female' left to the red bar, and 'male' left to the blue bar (currently, the text 'female' is right to the red bar, and 'male' right to the blue bar). – Rtist Jan 08 '20 at 13:44

1 Answers1

5

I hope this is what you wanted

library(ggplot2)

df = data.frame(
  x = c(1:10, 1:10),
  y = 1:20,
  group = rep(c('male', 'female'), each = 10))

ggplot(df, aes(x=x, y=y, color = group)) + 
  geom_smooth() +  
  theme(legend.position = 'right') + 
  guides(color = guide_legend(title.position = "top", 
                              # hjust = 0.5 centres the title horizontally
                              title.hjust = 0.5,
                              label.position = "left")) 
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2020-01-08 by the reprex package (v0.3.0)

amrrs
  • 6,215
  • 2
  • 18
  • 27
  • Can you explain what I am supposed to control with theme(), and what in guides()? Can't we control all parameters in theme()? Why controlling legend.text.align and legend.position in theme() but label.position in guides? – Rtist Jan 08 '20 at 16:05