I´m trying to make a filter for the labels in a ggplot
Here is my initial ggplot
library(tidyverse)
library(gapminder)
data("gapminder")
gapminder %>%
filter(year == 2007) %>%
ggplot(aes(x = gdpPercap, y = lifeExp, color = continent))+
geom_point() -> A
My limit value
limit_value <- 70
gapminder %>%
filter(year == 2007) %>%
subset(lifeExp> limit_value) -> my_labels
I want to do it using ifelse
A +
geom_text((aes(label = ifelse(lifeExp > limit_value, my_labels$country,""))))
In the variable labels$country I have the name of each country but I get this instead of the names.
Any help?
If you take a look at the column country, you'll see it is a Factor. When you use the "ifelse", it reduces the column to just the "levels". You could either wrap that in as.character, or use dplyr's "if_else" (which will do it as you expect). Here's both options:
gapminder %>%
filter(year == 2007) |>
mutate(label = if_else(lifeExp > limit_value,
as.character(country), "")) |> # set to character
ggplot(aes(x = gdpPercap, y = lifeExp,
color = continent))+
geom_point() +
geom_text(aes(label = label))
# or:
gapminder %>%
filter(year == 2007) |>
mutate(label = if_else(lifeExp > limit_value, #dplyr's if_else
country, "")) |>
ggplot(aes(x = gdpPercap, y = lifeExp,
color = continent))+
geom_point() +
geom_text(aes(label = label))