2

I have a question about the binwidth in ggplot in r.

I have two sets of data, one called "error_hat" and one called "error_tilde". I have made their histogram separately, and I see they are similar to each other.

enter image description here

enter image description here

Now I want to put them together to make a comparison. My code is as followed:

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()

It produces a picture like this:

enter image description here

I am wondering why the data in the middle has a different width (since I have set all the width to be 0.03)?

Could anyone help me with this problem? Many thanks!

divibisan
  • 11,659
  • 11
  • 40
  • 58
Yingze Hou
  • 21
  • 2
  • 2
    `binwidth` doesn't refer to the width of the bars as they appear on the chart, it refers to how your data is "binned" into groups to make a histogram. So `binwidth = 0.03` means that, for example, values from 0 - 0.03 will be counted up to make one bar, and values from 0.03-0.06 will be counted up to make the 2nd bar, and so on. – divibisan Jan 16 '19 at 01:09
  • 2
    Possible duplicate of [Bars in geom\_bar are not of equal width](https://stackoverflow.com/questions/46048925/bars-in-geom-bar-are-not-of-equal-width) – divibisan Jan 16 '19 at 01:11

1 Answers1

1

This is a consequence of using dodge2 versus dodge. This is the expected behavior as outlined here.

Maybe you want regular dodge instead?

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()

Created on 2019-01-15 by the reprex package (v0.2.1)

Chase
  • 67,710
  • 18
  • 144
  • 161