【问题标题】:Filling bar colours with the mean of another continuous variable in ggplot2 histograms用ggplot2直方图中另一个连续变量的平均值填充条形颜色
【发布时间】:2021-10-29 03:06:45
【问题描述】:

我有一个市级数据集。我想绘制给定变量的直方图,同时用另一个连续变量(使用颜色渐变)填充条形图。这是因为我认为,与分布上端的城市相比,我绘制直方图的变量值较低的城市的人口规模(平均而言)非常不同。

使用mtcar 数据,假设我想绘制mpg 的分布并用连续颜色填充条形以表示每个直方图条形的变量wt 的平均值。我在下面输入了代码,但我不知道如何让fill 选项取wt 的平均值。我想要一个带有颜色渐变的图例,以便告知每个直方图条的 wt 的平均值是否相对而言是低-中-高。

  mtcars %>% 
  ggplot(aes(x=mpg, fill=wt)) +
  geom_histogram()

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    这不是一个确切的直方图,而是我能想到的最接近您的问题的直方图

    library(tidyverse)
    
    mtcars %>%
      #Create breaks for mpg, where this sequence is just an example
      mutate(mpg_cut = cut(mpg,seq(10,35,5))) %>% 
      #Count and mean of wt by mpg_cut
      group_by(mpg_cut) %>% 
      summarise(
        n = n(),
        wt = mean(wt)
      ) %>% 
      ggplot(aes(x=mpg_cut, fill=wt)) +
      #Bar plot 
      geom_col(aes(y = n), width = 1)
    

    【讨论】:

      【解决方案2】:

      如果您想要一个真正的直方图,您需要先通过汇总来转换您的数据,然后使用geom_col 而不是geom_histogram 进行绘图。基本 R 函数hist 将帮助您在这里生成中断点和中点:

      library(ggplot2)
      library(dplyr)
      
      mtcars %>% 
        mutate(mpg = cut(x      = mpg, 
                         breaks = hist(mpg, breaks = 0:4 * 10, plot = FALSE)$breaks,
                         labels = hist(mpg, breaks = 0:4 * 10, plot = FALSE)$mids)) %>%
        group_by(mpg) %>%
        summarize(n = n(), wt = mean(wt)) %>%
        ggplot(aes(x = as.numeric(as.character(mpg)), y = n, fill = wt)) +
        scale_x_continuous(limits = c(0, 40), name = "mpg") +
        geom_col(width = 10) +
        theme_bw()
      

      【讨论】:

      • 哇,使用 hist() 函数获取中断和标签非常有创意!
      • 太棒了!这正是我一直在寻找的。最后一个问题:如何定义 x 轴上显示的标签?假设我希望它显示从 0 到 40,间隙间隔 od 10?
      猜你喜欢
      • 2019-01-30
      • 2018-08-30
      • 1970-01-01
      • 2015-04-04
      • 2023-03-19
      • 1970-01-01
      • 2020-07-24
      • 2019-12-24
      • 1970-01-01
      相关资源
      最近更新 更多