ordinatous
ordinatous

Reputation: 1

How to change legend in ggplot2?

I do the exercice with iris data set. I almost do what I want, but the the legend appear twice .

Is it possible to "translate" the legend ? If I try with : scale_color_discrete see the result below.

library(ggplot2)
library(ggdark)
ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width )) +
  geom_point(aes(color=Species, shape=Species)) +
  xlab("Longueur des sépales") + 
  ylab("Largeur des sépales") +
  ggtitle("Largeur et longueur des sépales") +
    scale_color_discrete(name = "Espèces") +
    dark_theme_gray() +
   theme(plot.title = element_text(family = "Roboto"),
        plot.background = element_rect(fill = "grey10"),
        panel.background = element_blank(),
        panel.grid.major = element_line(color = "grey30", size = 0.2),
        panel.grid.minor = element_line(color = "grey30", size = 0.5),
        legend.background = element_blank(),
        axis.ticks = element_blank(),
        legend.key = element_blank(),
        legend.position = c(0.815, 0.85))

And the result:

Result iris_1

And if I try with label:

library(ggplot2)
library(ggdark)
ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width )) +
  geom_point(aes(color=Species, shape=Species)) +
  labs(title = "Largeurs et longueurs des sépales par espèce",
        caption = "Jeu de donnée iris",
         x = "Longueur des sépales",
         y = "Largeur des sépales",
         colour = "Espèces"
     ) +
   theme(
     plot.title = element_text(family = "Roboto"),
        plot.background = element_rect(fill = "grey10"),
        panel.grid.major = element_line(color = "grey30", size = 0.2),
        panel.grid.minor = element_line(color = "grey30", size = 0.5),
        legend.background = element_blank(),
        axis.ticks = element_blank() 
     ) +
    dark_theme_gray()

Result iris_2

There is something that I don't understand. Thanks .

Upvotes: 0

Views: 134

Answers (1)

Kra.P
Kra.P

Reputation: 15123

Adding scale_shape_discrete(name = "Espèces") will do.

ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width,color=Species, shape=Species )) +
  geom_point(aes()) +
  xlab("Longueur des sépales") + 
  ylab("Largeur des sépales") +
  ggtitle("Largeur et longueur des sépales") +
  scale_color_discrete(name = "Espèces") +
  scale_shape_discrete(name = "Espèces") +
  dark_theme_gray() 

enter image description here

Upvotes: 1

Related Questions