自定义x轴刻度以在直方图中显示范围?

时间:2020-04-20 10:42:27

标签: r ggplot2 histogram

下面的代码

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

生成图

enter image description here

如您所见,x轴显示数据范围内整数的刻度,但是这些刻度不一定能很好地反映此直方图中每个bin中包含的实际数据范围。

有没有办法修改此脚本以允许x轴显示每个bin的真实范围?

1 个答案:

答案 0 :(得分:2)

我认为您希望使用breaks而不是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