如何在 R 中使用 ggplot2 将直方图中的 X 轴标签设置在中心的?


geom_histogram 函数的边界参数和 scale_x_continuous 函数的断口参数可以帮助我们在使用 ggplot2 时将直方图中的 X 轴标签设置在中心。我们需要谨慎选择边界和断口,具体取决于 X 轴值的比例。查看以下示例了解如何操作。

示例

考虑以下数据帧 −

示例

实时演示

> x<-rpois(20,5)
> df<-data.frame(x)
> df

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

x
1 5
2 7
3 6
4 4
5 7
6 7
7 10
8 3
9 6
10 6
11 5
12 4
13 4
14 6
15 7
16 4
17 1
18 11
19 6
20 9

加载 ggplot2 包并创建直方图 −

示例

> library(ggplot2)
> ggplot(df,aes(x))+ geom_histogram(binwidth=1)

输出

创建 X 轴标签位于中心的直方图 −

示例

>ggplot(df,aes(x))+geom_histogram(binwidth=1,boundary=-0.5)+ scale_x_continuous(breaks=1:11)

输出

更新日期:2021-05-01

6 千多阅读量

开启你的职业生涯

完成课程,获得认证

开始学习
广告