Illimar Rekand
Illimar Rekand

Reputation: 103

Customize x-axis ticks to display range in a histogram?

The following code below

library("ggplot2")
library("datasets")
data(iris)

iris.hist <- ggplot(iris, aes(x = Sepal.Length)) +
                      geom_histogram(data = subset(iris, Species == "setosa"), bins = 5, fill = "black", color = "black") +
                      geom_histogram(data = subset(iris, Species == "versicolor"), bins = 5, fill = "white", color = "black")


iris.hist

generates the plot

enter image description here

As you can see, the x-axis shows ticks for the integers in the data range, but these ticks do not necessarily reflect very well the real data range contained in each bin in this histogram.

Is there a way I could modify this script to allow the x-axis to show the real range of each bin?

Upvotes: 1

Views: 2036

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

I think you want breaks instead of bins:

mybreaks <- c(3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5)

ggplot(iris, aes(x = Sepal.Length)) +
  geom_histogram(data = subset(iris, Species == "setosa"), 
                 breaks = mybreaks, fill = "black", color = "black") +
  geom_histogram(data = subset(iris, Species == "versicolor"), 
                 breaks = mybreaks, fill = "white", color = "black") +
  scale_x_continuous(breaks = mybreaks)

enter image description here

Upvotes: 2

Related Questions