Как мне изменить форму символов легенды ggplot?

#r #ggplot2

#r #ggplot2

Вопрос:

Я использую ggplot для визуализации набора данных gapminder. Может кто-нибудь помочь мне заставить легенду показывать круглые точки с их размерами, соответствующими населению страны?

 df1<-gapminder[!(gapminder$country=="Kuwait"),]

blackline <- df1 %>% 
  group_by(continent, year) %>% 
  summarise(average = weighted.mean(gdpPercap))

p <- ggplot(data = df1, mapping = aes(x = year, y = gdpPercap))   
  scale_x_continuous(breaks = seq(1960, 2000, by = 20))  
  theme_bw()  
  labs(x = "Life Expectancy",
       y = "GDP Per Capita",
        color = "Continent",
        size = "Population (100K)")  
  # colored dots
  geom_point(df1, mapping = aes(col = continent, size = pop/100000))  
  # colored lines
  geom_line(data = df1, aes(color = continent, group = country))  
  facet_grid(cols = vars(continent))  
  # weighted average black line
  geom_line(data = blackline, aes(x = year, y = average, size = 1))  
  geom_point(data = blackline, aes(x = year, y = average, size = 1000))

p 
  

вывод ggplot

Ответ №1:

Этого можно добиться, установив show.legend=FALSE геометрию для черной линии:

 library(gapminder)
library(ggplot2)
library(dplyr)

df1<-gapminder[!(gapminder$country=="Kuwait"),]

blackline <- df1 %>% 
  group_by(continent, year) %>% 
  summarise(average = weighted.mean(gdpPercap))
#> `summarise()` regrouping output by 'continent' (override with `.groups` argument)

p <- ggplot(data = df1, mapping = aes(x = year, y = gdpPercap))   
  scale_x_continuous(breaks = seq(1960, 2000, by = 20))  
  theme_bw()  
  labs(x = "Life Expectancy",
       y = "GDP Per Capita",
       color = "Continent",
       size = "Population (100K)")  
  # colored dots
  geom_point(aes(col = continent, size = pop/100000))  
  # colored lines
  geom_line(aes(color = continent, group = country))  
  facet_grid(cols = vars(continent))  
  # weighted average black line
  geom_line(data = blackline, aes(x = year, y = average, size = 1), show.legend = FALSE)  
  geom_point(data = blackline, aes(x = year, y = average, size = 1000), show.legend = FALSE)

p