Home > OS >  Combine ggflags with linear regression in ggplot2
Combine ggflags with linear regression in ggplot2

Time:04-03

I have data that looks like this:

enter image description here

I want to run a linear regression model on it and instead of the usual dots use country flags using ggflas (enter image description here

Do you have any idea why and how I could get both the flags and the regression line in the same plot?

CodePudding user response:

You could achieve your desired result by adding the group=1 aesthetic to geom_smooth. Otherwise your data gets grouped by country and you end up with only one obs per country so that you don't get a line:

library(ggplot2)
library(ggflags)

set.seed(123)

Data <- data.frame(
  country = c("at", "be", "dk", "fr", "it"),
  x = runif(5),
  y = runif(5)
)

ggplot(Data, aes(x = x, y = y, country = country, size = 11))  
  geom_flag()  
  scale_country()  
  scale_size(range = c(10, 10))  
  geom_smooth(aes(group = 1), method = "lm", se = FALSE, size = 1)
#> `geom_smooth()` using formula 'y ~ x'

  • Related