Home > Blockchain >  geom_smooth and geom_point do not have legends
geom_smooth and geom_point do not have legends

Time:11-27

I want to create a plot that looks like this: enter image description here

x=1:20
y=sample(20)

df <- tibble(x=x,y=y)
ggplot(df,aes(x,y)) 
  geom_smooth() 
  geom_point()

But the codes unabled to show legends. Could anyone help me, thanks!

CodePudding user response:

You could set them inside their aes() as variables:

x <- 1:20
y <- sample(20)

library(ggplot2)
library(dplyr)

df <- tibble(x=x,y=y)

ggplot(df,aes(x,y)) 
  geom_smooth(aes(color = "line")) 
  geom_point(aes(color = "point")) 
  scale_color_manual(values = c("blue","red"))

enter image description here

CodePudding user response:

I'm perhaps being a bit over-literal in your requirements, but you could do:

tibble(x = 1:20, y = sample(20)) %>%
  ggplot(aes(x, y))  
  geom_smooth(aes(linetype = "line"))  
  geom_point(aes(shape = "point"), color = "red", size = 3)  
  theme_gray(base_size = 20)  
  theme(legend.position = c(0.75, 0.9),
        legend.background = element_blank())  
  labs(shape = NULL, linetype = NULL) 

enter image description here

CodePudding user response:

With ggnewscale you could try:

library(tibble)
library(ggplot2)
library(ggnewscale)


x=1:20
y=sample(20)

df1 <- tibble(x=x, y=y)

ggplot(df1, aes(x, y)) 
  geom_smooth(aes(colour = "line")) 
  scale_colour_manual(values = "black")  
  labs(colour = NULL) 
  new_scale_colour() 
  geom_point(aes(colour = "point")) 
  scale_colour_manual(values = "red") 
  labs(colour = NULL)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Created on 2022-11-27 with reprex v2.0.2

  • Related