ggplot: modify geom_point() for a particular category

In the example below, how can I change the size and shape of the points for a particular country, say, for Sweden?

library(tidyverse)
library(gapminder)
gapminder %>% 
  filter(country %in% c("Norway", "Sweden", "Finland")) %>% 
  ggplot(aes(x = year, y = lifeExp, color = country)) +
  geom_point()

Created on 2020-07-02 by the reprex package (v0.3.0)

I would suggest adding shape or size to the aes mapping and then manually setting the values so that there is only one legend. Example of changing the shape for Sweden, which is essentially forcing the shapes for Finland and Norway to be the same:

library(tidyverse)
library(gapminder)
gapminder %>% 
  filter(country %in% c("Norway", "Sweden", "Finland")) %>% 
  ggplot(aes(x = year, y = lifeExp, color = country, shape = country)) +
  geom_point()+
  scale_shape_manual(values = c(16,16,17))
4 Likes

Some other approaches, depending how you want to organize your legend (or if you want any at all):

library(tidyverse)
library(gapminder)

gapminder %>% 
  filter(country %in% c("Norway", "Sweden", "Finland")) %>% 
  ggplot(aes(x = year, y = lifeExp, color = country, size = country == "Sweden", shape = country == "Sweden")) +
  geom_point() + 
  scale_color_discrete(name = "Country") +
  scale_shape_discrete(guide = FALSE) +
  scale_size_discrete(guide = FALSE)
#> Warning: Using size for a discrete variable is not advised.


gapminder %>% 
  filter(country %in% c("Norway", "Sweden", "Finland")) %>% 
  mutate(country = if_else(country == "Sweden", "Sweden", "Other")) %>% 
  ggplot(aes(x = year, y = lifeExp, color = country, size = country, shape = country)) +
  geom_point() + 
  scale_color_discrete(name = "Country") +
  scale_shape_discrete(name = "Country") +
  scale_size_discrete(name = "Country")
#> Warning: Using size for a discrete variable is not advised.

Created on 2020-07-02 by the reprex package (v0.3.0)

1 Like

Many thanks @toryn_stat and @Z3tt!

1 Like

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