Coloring specific points in Ggplot - R

Asked

Viewed 196 times

2

I’m doing a graphical analysis of the package data gapminder. Soon, I made the following code:

library('gapminder')
dados6 <- gapminder

ggplot(gapminder, aes(x = continent, y = lifeExp)) +
  geom_boxplot(outlier.colour = "hotpink") +
  geom_jitter(position = position_jitter(width = 0.1, height = 0), alpha = 1/4)

In which produced the chart below:

inserir a descrição da imagem aqui

However, I want to color with green the points referring to Brazil.
How can I do that?

Sincerely yours.

1 answer

4


You can do it with one more geom_, to geom_point. However, to have only the points referring to Brazil, you have to select a subset of the data, in this case with subset.

library(tidyverse)
library(ggplot2)
library('gapminder')


gapminder %>%
  group_by(continent) %>%
  mutate(ymax = quantile(lifeExp, 3/4) + IQR(lifeExp),
         ymin = quantile(lifeExp, 1/4) - IQR(lifeExp),
         out = lifeExp < ymin | lifeExp > ymax) %>%
  ggplot(aes(x = continent, y = lifeExp)) +
  geom_boxplot(outlier.colour = "hotpink") +
  geom_jitter(aes(y = ifelse(out, NA, lifeExp)),
              position = position_jitter(width = 0.1, height = 0), alpha = 1/4) +
  geom_point(data = subset(gapminder, country == 'Brazil'),
             aes(x = continent, y = lifeExp),
             position = position_jitter(width = 0.1),
             colour = "green", alpha = 1/2)

inserir a descrição da imagem aqui

  • 1

    I didn’t understand the outliers in this view and AP’s. Note that there is a black dot next to each pink outlier. It seems that both geom_jitter and geom_boxplot are cramming the outliers, but only the geom_boxplot the pink spots. I believe there is an unnecessary duplication of these aberrant spots, but only of them. That is, the geom_jitter ends up making the outliers appear all bent, leading the user to believe that there are twice as many outliers in this data set.

  • 1

    @Marcusnunes Done, I believe you’re right now.

  • Excelente, Rui!

  • Well-signposted!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.