【问题标题】:Histogram with multiple bins and groups具有多个 bin 和组的直方图
【发布时间】:2020-07-17 19:59:15
【问题描述】:

我试图在 R 中重现在 excel 中创建的这三个简单的直方图,以便让一些东西更吸引人的眼球。我毫不怀疑这很简单,但我没有使用 R。

[

我找到了用于生成基本直方图的不同教程,但还没有找到可以为每个距离箱生成三列(代表年份),然后为每个数据组(A、B , C).
我相信我需要做的第一件事是重组我的数据,我想这是我不确定的步骤。

提前致谢。

【问题讨论】:

  • 请查看How to make a great R reproducible example,以修改您的问题,并从您的数据中提取更小的样本(查看?dput())。发布您的数据或没有数据的图像会使我们难以为您提供帮助!
  • 将您的数据导入 R 并使用 dput()。将结果粘贴到您的问题中。您的数据图片对于向您展示如何在 R 中做某事没有帮助。分组条形图(不是直方图)很容易做到。

标签: r ggplot2 plot histogram


【解决方案1】:

是的,您将不得不重组您的数据。如@stefan 所示,您可以在 R 中完成,或者如果它具有挑战性,您可以在 excel 本身中完成。整洁的数据易于绘制和分析(请参阅section 12.1 了解整理数据,section 3.7, 3.8 了解可视化)。整洁的数据看起来像是由四列组成 - 距离、价值、价值_年、价值_组。

例如,我将一些数据存储为制表符分隔的文件 (testdata.txt) 并使用 tidyverse 的 read_delim 函数读取。以下是示例代码:

library(tidyverse)
foo <- read_delim("testdata.txt", delim = "\t")
foo %>% mutate(Val_year = factor(Val_year, levels=c("2015","2016","2017"))) %>% 
ggplot() + geom_bar(aes(x=Dist, y=Val, fill = Val_year), stat = "identity", position = "dodge") + facet_grid(.~Val_grp)

【讨论】:

    【解决方案2】:

    使用一些随机示例数据,以下代码是一个tidyverse 解决方案,它为您提供一个条形图或柱形图(因为您的数据已经分箱,这是要走的路)模仿您的一个数据集的 Excel 图表。正如您已经猜到的那样,棘手的部分是将您的数据放入 R 中(为此:查看readxl 包)并重新排列它以进行绘图(这是通过pivot_longer 来自tidyr 包和@ 987654327@ from dplyr 两者都是tidyverse 的一部分。至于绘图部分我使用ggplot2 是-你可能已经猜到了(;-也是tidyverse 的一部分。

    # Example data set
    set.seed(42)
    
    df <- data.frame(
      distance = paste0(seq(0, 3.5, by = 0.5), "-", seq(0.5, 4, by = 0.5)),
      `2015` = round(runif(8) * 8, 0),
      `2016` = round(runif(8) * 8, 0),
      `2017` = round(runif(8) * 8, 0)
    )
    df
    #>   distance X2015 X2016 X2017
    #> 1    0-0.5     7     5     8
    #> 2    0.5-1     7     6     1
    #> 3    1-1.5     2     4     4
    #> 4    1.5-2     7     6     4
    #> 5    2-2.5     5     7     7
    #> 6    2.5-3     4     2     1
    #> 7    3-3.5     6     4     8
    #> 8    3.5-4     1     8     8
    
    library(tidyverse)
    
    df %>% 
      # Convert the dataset to long format
      pivot_longer(-distance, names_to = "Year", values_to = "Value") %>% 
      # format the dates, get rid of leading Xs
      mutate(Year = gsub("^X", "", Year)) %>% 
      ggplot(aes(distance, Value, fill = Year)) + 
      # Column chart. Add some width between columns
      geom_col(position = position_dodge2(2)) +
      scale_y_continuous(expand = expansion(mult = c(0, .05))) +
      scale_fill_manual(values = c("blue", "orange", "grey")) +
      # Get rid of axis and legend labels
      labs(y = "", x = "", fill = "") +
      theme_bw() +
      theme(legend.position = "bottom")
    

    reprex package (v0.3.0) 于 2020 年 4 月 5 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2021-09-03
      • 2017-04-23
      • 2014-12-24
      相关资源
      最近更新 更多