简体   繁体   中英

Multiple lines in ggscatter plot

Hi I'm currently learning R programming in my sociology bachelor and I came to the problem that I cant implement two regression lines in a scatter plot. My code that I've written so far is the following:

#Value 1 and 2 from the first country
Lrscaleger <- c(4.535469,4.53125,4.515967,4.500684,4.446576,4.392469,4.390175,4.387881)
DomMusGer <- c(6,10,4,14,13,10,8,17)
GER <- data.frame(Lrscaleger,DomMusGer)

#Value 1 and 2 from the second country
Lrscalech <- c(5.136263,5.153846,5.148803,5.143759,5.103913,5.064067,5.079669,5.095272)
DomMusCH <- c(2,3,2,2,1,0,2,2)
CH <- data.frame(Lrscalech,DomMusCH)

#Scatterplot for Country Nr. 1
ggscatter(GER,
          x = "Lrscaleger",
          y="DomMusGer",
          color="black",
          add="reg.line",
          xlab = "Politische Ausrichtung von 0(Links) - 10(Rechts)",
          ylab= "Künstler:innen einheimisch")

#Scatterplot for Country Nr. 2
ggscatter(CH,
          x = "Lrscalech",
          y = "DomMusCH",
          color="black",
          add="reg.line",
          xlab = "Politische Ausrichtung von 0(Links) - 10(Rechts)",
          ylab= "Künstler:innen einheimisch")

TBMK I'm afraid that this is not possible via ggpubr::ggscatter . I checked the docs and couldn't find an option to eg map a third variable on colorer... Instead I would suggest to simply use ggplot2`.

To this end you first have to combine you country datasets using eg dplyr::bind_rows . However, as the columns in your datasets have a suffix corresponding to the county code we first have to rename the columns.

library(ggplot2)
library(dplyr)
library(ggpubr)

CH <- rename(CH, Lrscale = Lrscalech, DomMus = DomMusCH)
GER <- rename(GER, Lrscale = Lrscaleger, DomMus = DomMusGer)

CH_GER <- list(CH = CH, GER = GER) %>% 
  dplyr::bind_rows(.id = "country")

ggplot(CH_GER, aes(Lrscale, DomMus, color = country)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  ggpubr::theme_pubr() +
  labs(x = "Politische Ausrichtung von 0(Links) - 10(Rechts)",
       y= "Künstler:innen einheimisch")
#> `geom_smooth()` using formula 'y ~ x'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM