【问题标题】:Histogram not showing correct count/values? (Histogram vs Geom Freqpoly)直方图未显示正确的计数/值? (直方图 vs Geom Freqpoly)
【发布时间】:2020-11-01 06:34:54
【问题描述】:

我有一个 2002 年纽约马拉松赛和每个人的地点的数据集。我也有每个人的性别。

当我绘制一个按性别分组的直方图时,女性的计数是关闭的!

当我绘制 FreqPoly 图时,根据数据,分布符合预期。

谁能解释这种差异?红色条用于女性,蓝色条用于男性。相同的颜色适用于 freq_poly 图。

红线是女性赛车手的计数应该在的位置,但直方图显示的数值要高得多。为什么?

【问题讨论】:

  • 如果你使用geom_histogram(..., position = "identity")而不是默认的("stack"),他们可能会一个接一个
  • 如果您希望能够看到所有相邻的栏,请尝试geom_histogram(..., position = "dodge")

标签: r ggplot2 histogram


【解决方案1】:

要详细说明 teunbrand 在评论中所说的内容,问题是您的直方图条相互堆叠。这是因为geom_histogram 的默认位置参数是position = "stack"。这与默认为position = "identity"geom_freqpoly 不同。

因此,您只需添加position = "identity"

data(nym.2002, package = "UsingR")
ggplot(nym.2002, aes(x = place)) + 
  geom_freqpoly(aes(color = gender)) + 
  geom_histogram(aes(fill = gender),
                 alpha = 0.2,
                 position = "identity")

如果您查看help(geom_freqpoly),您可以找到自己的默认参数。

【讨论】:

    【解决方案2】:

    不是答案,而是 Ian Campbell 和 teunbrand 的答案中讨论的不同职位选项的可视化

    
    library(ggplot2)
    set.seed(1)
    p1 <- ggplot()+
      geom_histogram(data = data.frame(x = rnorm(100), g = rep(1:2, 50)), aes(x, fill = factor(g)), position = "dodge")+
      ggtitle("position = dodge")
    
    set.seed(1)
    p2 <- ggplot()+
      geom_histogram(data = data.frame(x = rnorm(100), g = rep(1:2, 50)), aes(x, fill = factor(g)), position = "identity")+
      ggtitle("position = identity")
    
    set.seed(1)
    p3 <- ggplot()+
      geom_histogram(data = data.frame(x = rnorm(100), g = rep(1:2, 50)), aes(x, fill = factor(g)))+
      ggtitle("position = stack")
    
    
    library(patchwork)
    
    p1/p2/p3
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    

    reprex package (v0.3.0) 于 2020-07-11 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2016-08-29
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多