简体   繁体   中英

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:

结果 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()

结果 iris_2

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

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() 

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM