如何将直方图的条形与 x 轴对齐? [英] How to align the bars of a histogram with the x axis?

查看:22
本文介绍了如何将直方图的条形与 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)

这篇关于如何将直方图的条形与 x 轴对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆