I have data that looks like this:
I want to run a linear regression model on it and instead of the usual dots use country flags using ggflas (https://github.com/jimjam-slam/ggflags):
Data <- read.xlsx(
paste0(mainDirectory, "Data.xlsx"),
"Data")
ggplot(Data, aes(x = x, y = y, country=country, size = 11)) +
geom_flag() +
scale_country() +
scale_size(range = c(10, 10)) +
geom_smooth(method = "lm", se = FALSE)
This works fine, except for me not getting the regression line to show up:
Do you have any idea why and how I could get both the flags and the regression line in the same plot?
>Solution :
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'


