1

I have a fairly easy piece of code to visualize a few parameteres about a country.

data_verylong %>%
  filter(country %in% c("Germany")) %>%
  ggplot(aes(year, value, color=indicator))+
  geom_line()+
  facet_wrap(vars(indicator), scales = "free_y", ncol = 1, strip.position = "top")+
  theme(strip.background = element_blank(), strip.placement = "outside")

This is the result: desired outcome

However, I want do make this dynamic as I want to dynamically get the data about different countries. And this is my code for this

deepdive <- function(country) {
  data_verylong %>%
    filter(country == country)%>%
    ggplot(aes(year, value, color=indicator))+
    geom_line()+
    facet_wrap(vars(indicator), scales = "free_y", ncol = 1, strip.position = "top")+
    theme(strip.background = element_blank(), strip.placement = "outside")
}

deepdive("Germany")

bad result

For some reason, the result looks very different and unusable. Has anyone encountered sth similar and can help me?

Quinten
  • 35,235
  • 5
  • 20
  • 53
justforjan
  • 13
  • 3
  • use `filter(country == !!country)` instead of `filter(country == country)` in the function and it should work. – DaveArmstrong Oct 18 '22 at 16:49
  • Another approach would be to do `filter(country == .env$country)` using the `.env` pronoun from `rlang`. – stefan Oct 18 '22 at 17:10
  • To explain more, your problem is that `filter(country == country)` is checking if the country columns matches the country column, which it always will, so you are getting data for all the countries, without telling ggplot what distinguishes the country series, so each line it plots combines the data for all the countries, leading to the distinctive and infamous sawtooth patterns you see. The advice above is explaining how to turn the function input into a value that the `filter` can use. – Jon Spring Oct 18 '22 at 17:57

0 Answers0