How change the legend name position in ggplot2?

Hi comunity

Im want move the lengend name of the top the legend, but I dont know how to make this.

Maybe with legend.position is possible.

library(tidyverse)
# Example data
data <- data.frame(x = 1:3,                     
                   y = 1:3,
                   group = LETTERS[1:3])

ggplot(data, aes(x, y, color = group)) +    
  geom_point() +
  scale_color_manual(values = c("#E41A1C", "#377EBA", "#4BAD4A"), name='')+ # Im change name
  theme(legend.position = "bottom")+
  labs(x='')

The idea is put the legend name in this red square.

Tnks!

1 Like

Hi, @M_AcostaCH , you could use theme(legend.margin=margin(-10, 0, 0, 0)) .Follwing is the comparison.

library(tidyverse)
# Example data
data <- data.frame(x = 1:3,                     
                   y = 1:3,
                   group = LETTERS[1:3])

ggplot(data, aes(x, y, color = group)) +    
  geom_point() +
  scale_color_manual(values = c("#E41A1C", "#377EBA", "#4BAD4A"), name='')+ # Im change name
  theme(legend.position = "bottom")+
  labs(x='')+
  theme(legend.margin=margin(-10, 0, 0, 0)) 

Created on 2023-06-06 with reprex v2.0.2


1 Like

Hi @Comede_way , tnks!

But the idea is put the legend name in the top of legend attributes. Because de legend tittle is show in a left of this attributes.

Hi, @M_AcostaCH , it is you want,use label.position?

library(tidyverse)
# Example data
data <- data.frame(x = 1:3,                     
                   y = 1:3,
                   group = LETTERS[1:3])

p1<-ggplot(data, aes(x, y, color = group)) +    
  geom_point() +
  scale_color_manual(values = c("#E41A1C", "#377EBA", "#4BAD4A"), name='')+ # Im change name
  theme(legend.position = "bottom")+
  labs(x='')
p1

p2<-p1+guides(col = guide_legend(label.position = "top"))+guides(fill = guide_legend(title = NULL))+theme(legend.margin=margin(-10, 0, 0, 0)) 
p2

Created on 2023-06-08 with reprex v2.0.2

Or this? use tiltle.position

library(tidyverse)
# Example data
data <- data.frame(x = 1:3,                     
                   y = 1:3,
                   group = LETTERS[1:3])

p1<-ggplot(data, aes(x, y, color = group)) +    
  geom_point() +
  scale_color_manual(values = c("#E41A1C", "#377EBA", "#4BAD4A"), name='legen')+ # Im change name
  theme(legend.position = "bottom")+
  labs(x='')
p1

p2<-p1+guides(col = guide_legend(title.position = "top",title.hjust =0.5)) 
p2

The legend name you talk refer to "legend title"?

I mainly refer to the following link about legend guide.
Legend guide — guide_legend • ggplot2 (tidyverse.org)

1 Like

@Comede_way the best solution was with legend title section.
Tnks!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.