首页 > 解决方案 > R中的ggplot binwidth

问题描述

我对 r 中 ggplot 中的 binwidth 有疑问。

我有两组数据,一组称为“error_hat”,另一组称为“error_tilde”。我已经分别制作了它们的直方图,我发现它们彼此相似。

在此处输入图像描述

在此处输入图像描述

现在我想把它们放在一起做一个比较。我的代码如下:

catagory <- c(rep("error_hat",length(error_hat)) , rep("error_tilde",length(error_tilde)))

error <- c(error_hat, error_tilde)

error_data<-data.frame(catagory,error)

ggplot(error_data, aes(x=error,group=catagory,fill=catagory))+
  geom_histogram(position="dodge2", binwidth=0.03)+theme_bw()

它会产生这样的图片:

在此处输入图像描述

我想知道为什么中间的数据有不同的宽度(因为我已将所有宽度设置为 0.03)?

谁能帮我解决这个问题?非常感谢!

标签: rggplot2

解决方案


这是使用dodge2vs的结果dodge。这是此处概述的预期行为。

也许你想要常规dodge的?

library(ggplot2)
#fake data that mimics yours
set.seed(42)
error_hat <- runif(100)
error_tilde <- runif(100)
catagory <- c(rep("error_hat",length(error_hat)) , rep("error_tilde",length(error_tilde)))
error <- c(error_hat, error_tilde)
error_data<-data.frame(catagory,error)
ggplot(error_data, aes(x=error,group=catagory,fill=catagory))+
  geom_histogram(position="dodge", binwidth=0.03)+theme_bw()

reprex 包(v0.2.1)于 2019 年 1 月 15 日创建


推荐阅读