【问题标题】:Creating stratified histogram using an R function使用 R 函数创建分层直方图
【发布时间】:2020-09-13 06:14:39
【问题描述】:

我正在尝试在 R 上创建这个分层直方图,但是我没有得到正确的图。如果可能的话,我也想使用 rect 函数。

我将如何编写一个 R 函数来使用 R 中的 iris 数据集创建这个分层直方图?

这是目前为止的代码:

strathist = function(x, y, ylab = "Frequency", xlab = "", main = ""){
  
  cols = hcl(h=seq(0, 360, by = 120))
  
  h = hist(x, breaks = 24, plot = FALSE)
  
  tb = table(y, cut(x, h$breaks))
  
  
  plot.new()
  
  barplot(tb, ylim = c(0, max(h$count)), col = cols,
          ylab = ylab, xlab = xlab, main = main, axisnames = FALSE) 
  
  box()
  axis(1, 0:(length(h$breaks)-1), h$breaks)
  axis(2)
  

  
  legend("topright", c(rownames(tb)), fill = cols)
}

with(iris, strathist(Sepal.Width, Species, xlab = "Sepal.Width", main = "Stratified Histogram"))

【问题讨论】:

  • 嗨本杰门。你的错误是什么?您发布的图像是您想要实现的图像,还是您制作的情节?如果是这样,你认为它有什么问题?您能否编辑您的问题以提供更多详细信息,包括您使用的产生错误的代码。
  • 请不要破坏您自己的帖子。当您在此处发布时,即表示您授予 SO 在 CC-by SA 4.0 下分发内容的权利。任何破坏行为都将被撤销。如果您想删除您的问题,问题文本下方有一个“删除”链接。

标签: r function histogram


【解决方案1】:

有几种不同的方法可以做到这一点,如果你坚持使用 R 基础,你可以使用两个条形图,一个添加颜色,一个添加框:

strathist = function(x,
                     y,
                     ylab = "Frequency",
                     xlab = "",
                     main = "") {
  cols = hcl(h = seq(0, 360, by = 120))
  
  h = hist(x,
           breaks = 24,
           plot = F)
  
  tb = table(y, cut(x, h$breaks))
  
  
  ylim <- c(-.05 * max(colSums(tb)),
            1.25 * max(colSums(tb)))
  
  barplot(
    tb,
    col = cols,
    ylim = ylim,
    ylab = ylab,
    xlab = xlab,
    main = main,
    axisnames = FALSE,
    border = NA,
    space = 0
  )
  
  barplot(
    colSums(tb),
    ylim = ylim,
    col = NA,
    ylab = ylab,
    xlab = xlab,
    main = main,
    axisnames = FALSE,
    add = T,
    space = 0
  )
  
  box()
  axis(1, seq(0,
              length(h$breaks) - 1,
              by = 5),
              seq(min(x),max(x), by = .5))
  axis(2)
  
  legend("topright", c(rownames(tb)), fill = cols,border = NA,)
}

with(
  iris,
  strathist(Sepal.Width, Species, xlab = "Sepal.Width", main = "Stratified Histogram")
)

或者你可以走更简单的路线来使用ggplot2

library(ggplot2)

ggplot(iris,aes(x = Sepal.Width)) +
  geom_histogram(bins = 25,aes(fill = Species)) +
  geom_histogram(bins = 25, fill = NA, color = 'black') +
  theme_minimal()

reprex package (v0.3.0) 于 2020 年 9 月 13 日创建

【讨论】:

  • 是的,但我能想到的唯一方法是使用polygon 添加颜色,这可能有点烦人。
  • 是的,因为它只是多边形的包装器,但您仍然需要对坐标进行排序,这当然是可能的,但有点麻烦。
猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 2023-03-12
  • 2017-11-11
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
相关资源
最近更新 更多