Home > OS >  How to make smaller bubbels above bigger bubbels in ggplot2 R?
How to make smaller bubbels above bigger bubbels in ggplot2 R?

Time:12-05

In the plot, smaller bubbles will be hidden by bigger bubbles. if I use alpha, they will appear. I would like that small bubbles superpose the bigger ones without using alpha

   library(ggplot2)
   library(dplyr)

The dataset is provided in the gapminder library

    library(gapminder)
    data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)

    # Most basic bubble plot
   data %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
 ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent))  
geom_point(alpha=0.5)  
scale_size(range = c(.1, 24), name="Population (M)")

CodePudding user response:

The small points are already plotted over the large points. What you need is an outline on the points. You can do this by selecting shape = 21 and using the fill aesthetic for their overall color. Their outline can be whatever color you like, though here I have made them a darker version of the fill color, which gives a more subtle outline:

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

data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)

data %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
  ggplot(aes(gdpPercap, lifeExp, size = pop, fill = continent,
             color = after_scale(darken(fill, 0.3))))  
  geom_point(shape = 21)  
  scale_size(range = c(.1, 24), name = "Population (M)")  
  scale_x_continuous("GDP per Capita", labels = scales::dollar)  
  ylab("Life Expectancy")  
  theme_minimal(base_size = 20)  
  scale_fill_brewer(palette = "Pastel1")  
  ggtitle("Average life expectancy 2007")  
  guides(size = "none",
         fill = guide_legend(override.aes = list(size = 6)))  
  theme(panel.background = element_rect(fill = "gray95", color = NA),
        legend.title = element_text(size = 25, face = 2),
        legend.text = element_text(size = 25, face = 2))

enter image description here

CodePudding user response:

Here is another version of @Allan Cameron's solution:

# Libraries
library(ggplot2)
library(dplyr)
library(viridis)
library(gapminder)

gapminder %>% 
  filter(year=="2007") %>%
  select(-year) %>% 
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
  ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, fill=continent))  
  geom_point(alpha=0.5, shape=21, color="black")  
  scale_size(range = c(.1, 24), name="Population (M)", guide="none") 
  scale_fill_viridis(discrete=TRUE, option="A")  
  theme_bw()  
  theme(legend.position="bottom")  
  ylab("Life Expectancy")  
  xlab("Gdp per Capita") 

enter image description here

  • Related