代码之家  ›  专栏  ›  技术社区  ›  KGB91

在ggplot2中将ggflags与线性回归相结合

  •  0
  • KGB91  · 技术社区  · 4 年前

    我有如下数据:

    enter image description here

    我想在上面运行一个线性回归模型,用国旗代替通常的圆点 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)
    

    这很好,除了我没有显示回归线:

    enter image description here

    你知道为什么我可以在同一个图中得到这些标志和回归线吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   stefan    4 年前

    通过添加 group=1 审美 geom_smooth 。否则,您的数据将按 country 最终,每个国家只有一个OB,所以你不会得到一条线路:

    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'