Using the "secondary axis trick" with facets

Hi,

Following the "secondary axis trick" for direct labeling posted here: https://twitter.com/ClausWilke/status/1382451822053314562/photo/3

Does anyone know if this is possible to achieve with facets. Here is a reprex to work off of. As you can see, the same secondary axis labels are of course repeated on all facets.

library(tidyverse)
library(gapminder)

df <- 
  gapminder::gapminder |> 
  filter(continent %in% c('Oceania', 'Americas')) 

max_labs <-
  df |> 
  slice_max(year, by = country)

df |> 
  ggplot(aes(year, lifeExp, color = country)) +
  geom_line(show.legend = FALSE) +
  scale_y_continuous(
    limits = c(37, 82),
    sec.axis = dup_axis(
      breaks = max_labs$lifeExp,
      labels = max_labs$country,
      name = NULL
    )
  ) +
  facet_wrap(~ continent, scales = 'free_y')

Maybe you could play around with ggrepel: from Examples • ggrepel

You could do this better, but something to start with:

library(tidyverse)
library(gapminder)
library(ggrepel)

df <- 
  gapminder::gapminder |> 
  filter(continent %in% c('Oceania', 'Americas')) 

max_labs <-
  df |> 
  slice_max(year, by = country)


df |> 
  ggplot(aes(year, lifeExp, colour = country)) +
  geom_line(show.legend = FALSE) +
  facet_wrap(~ continent, scales = 'free_y') +
  geom_text_repel(data = max_labs,
                  aes(year, lifeExp, label = country),
                  nudge_x = -2, direction = "y", hjust = "right") +
  guides(colour = "none") 

Hi @mattwarkentin, I don't know if you can use a more detailed classification for each country, so you could avoid overlapping in some cases. For example America can be divided a bit more.

library(countrycode) # other continent classification 
library(ggrepel)

df <- gapminder |> 
  mutate(continent_2 = countrycode(country, "country.name", "region")) |> 
  filter(continent %in% c('Oceania', 'Americas')) 

max_labs <-
  df |> 
  slice_max(year, by = country)

# And take the plot of @williaml user
df |> 
  ggplot(aes(year, lifeExp, colour = country)) +
  geom_line(show.legend = FALSE) +
  facet_wrap(~ continent_2, scales = 'free_y') +
  geom_text_repel(data = max_labs,
                  aes(year, lifeExp, label = country),
                  nudge_x = -2, direction = "y", hjust = "right") +
  guides(colour = "none") 

# Latin America & Caribbean it is possible to break it down a little more in center and south, 
# but I don't know if the graph is useful for you. 

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.