如何将直方图的条形与 x 轴对齐?
问题描述:
考虑这个简单的例子
library(ggplot2)
dat <- data.frame(number = c(5, 10, 11 ,12,12,12,13,15,15))
ggplot(dat, aes(x = number)) + geom_histogram()
看到条形如何奇怪地与 x 轴对齐了吗?为什么 5.0
左侧的第一个条形而 10.0
处的条形居中?我怎样才能控制它?例如,(对我而言)让栏从标签右侧开始会更有意义.
See how the bars are weirdly aligned with the x axis? Why is the first bar on the left of 5.0
while the bar at 10.0
is centered? How can I get control over that? For instance, it would make more sense (to me) to have the bar starting on the right of the label.
答
这将使栏以值为中心
data <- data.frame(number = c(5, 10, 11 ,12,12,12,13,15,15))
ggplot(data,aes(x = number)) + geom_histogram(binwidth = 0.5)
这是一个带有刻度标签的技巧,可以让条形图在左侧对齐.但是如果你添加其他数据,你也需要移动它们
Here is a trick with the tick label to get the bar align on the left.. But if you add other data, you need to shift them also
ggplot(data,aes(x = number)) +
geom_histogram(binwidth = 0.5) +
scale_x_continuous(
breaks=seq(0.75,15.75,1), #show x-ticks align on the bar (0.25 before the value, half of the binwidth)
labels = 1:16 #change tick label to get the bar x-value
)
其他选项:binwidth = 1,breaks=seq(0.5,15.5,1)
(可能对整数更有意义)
other option: binwidth = 1, breaks=seq(0.5,15.5,1)
(might make more sense for integer)