Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine ggflags with linear regression in ggplot2

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 (https://github.com/jimjam-slam/ggflags):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

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?

>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'

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading