【问题标题】:Issue overlapping ggplot2 histograms with diff variables发出带有差异变量的重叠 ggplot2 直方图
【发布时间】:2020-06-03 12:56:21
【问题描述】:

我有一个数据框(下面的快照 - 它实际上有超过 12,000 个观察值),我可以在其中使用 ggplot 并构建一个直方图来单独描述每个变量的分布。我现在有兴趣将我构建的 3 个直方图叠加起来创建一个“单一”直方图。

我已尝试根据a similar question that was asked previously 改编以下建议,

d = data.frame(x = c(data1, data2), 
               type=rep(c("A", "B"), c(length(data1), length(data2))))
ggplot(d) + 
  geom_density(aes(x=x, colour=type))

但我不断收到以下错误:

#combinedImputedDataVis is a data frame
distr <- combinedImputedDataVis[,37:39]
ggplot(distr) + geom_density(aes(x=c(rt,controlt,cleart),
                                 type=rep(c("rt","controlt","cleart"),c(length(rt),length(controlt),length(cleart)))))

Error: Aesthetics must be either length 1 or the same as the data (12687): x and type
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
Ignoring unknown aesthetics: type 

不知道我哪里错了,希望有第二双眼睛

【问题讨论】:

  • data1data2 是原子数值类型吗?因为我从链接的答案中获取了data1data2,并且 ggplot2 v3.3.0 没有错误
  • 我更新了我的问题以包含我根据之前提供的解决方案创建的代码

标签: r ggplot2


【解决方案1】:

使用您问题中的图片所示的原始数据框:

d <- structure(list(rt = c(15, 173, 66, 167, 341), controlt = c(1294, 
181, 145, 835, 675), cleart = c(1603, 3274, 722, 1059, 2468)), 
class = "data.frame", row.names = c(NA, -5L))

d
#>    rt controlt cleart
#> 1  15     1294   1603
#> 2 173      181   3274
#> 3  66      145    722
#> 4 167      835   1059
#> 5 341      675   2468

那么如果数据是这种格式,最简单的方法是为每一列做一个单独的geom:

ggplot(d) + 
  geom_density(aes(x = rt), fill = "red", alpha = 0.5) + 
  geom_density(aes(x = controlt), fill = "green", alpha = 0.5) + 
  geom_density(aes(x = cleart), fill = "blue", alpha = 0.5)

但最好重新调整数据以将所有变量名称放入一列,并将它们的所有值放入另一列。这样就更容易控制情节的各个方面:

library(dplyr)

d %>% 
  pivot_longer(everything()) %>%
  ggplot(aes(x = value, fill = name)) + 
  geom_density(alpha = 0.5)

【讨论】:

    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多