ggplot2, how to shift histogram?

Viewed 125

I am trying to learn R and I just started this by going through the book "Hands-On Programming with R". I encountered a problem and can't continue because it bothers me a lot. As an exercise, I'm supposed to experiment with the ggplot2 package and make a histogram. The code to be used is as follows:

x <- c(1, 2, 2, 2, 3, 3)

qplot(x, binwidth = 1)

and the histogram should look like that in picture one. However, when I run the code my histogram doesn't look like the one in the picture (even though it should) and looks like that in picture 2. It's basically the same but 0.5 decimals to the left of where it should be.

Can some please tell me why doesn't the histogram look the same as in picture 1 and how to fix the code to make it look like that?

Picture 1: https://i.stack.imgur.com/dssBQ.jpg Picture 2: https://i.stack.imgur.com/wUk1i.jpg

2 Answers

I'm using ggplot2_3.3.2 with R version 4.0.3.

I get the same graph as you do rather than the plot as set out in https://rstudio-education.github.io/hopr/packages.html#packages-1.

I couldn't find which version of ggplot is used in the book, possibly from around 2014 based on some of the text. Bearing in mind @the_one_neuron's comment I suspect that this has something to do with changes to ggplot2 since the book was written.

The issue is one of binning or more colloqually 'gates and posts': you want the value 1 to be binned between 1 and <2 (centred on 1.5) rather than between 0 and 1 (centred on 0.5).

There is a much more detailed explanation from @r2evans at Why does geom_histogram start at negative bin lower limit even though all values are > 0?.

Anyways here's a fudge to get the result similar to your expected graph.


library(ggplot2)

x <- c(1, 2, 2, 2, 3, 3)

qplot(x, binwidth = 1, breaks = 1:4 - 0.000001, xlim = c(0, 4))

Created on 2021-01-15 by the reprex package (v0.3.0)

You could try to do something like this. It's not perfect but it is very close

qplot(x, binwidth = 1, xlim =c(0,NA), ylab = "count")
Related