【发布时间】:2021-01-05 08:06:25
【问题描述】:
我正在尝试更改 x 轴上的 x 标签在 ggplot2 直方图中的表示方式,以便显示为 0-10、10-20、20-30,而不是 0、10、20、30, 30-40等
我知道这可以手动完成,但我想知道是否有更简单的方法。
【问题讨论】:
我正在尝试更改 x 轴上的 x 标签在 ggplot2 直方图中的表示方式,以便显示为 0-10、10-20、20-30,而不是 0、10、20、30, 30-40等
我知道这可以手动完成,但我想知道是否有更简单的方法。
【问题讨论】:
假设你有这样的数据:
set.seed(123)
vec <- sample(1:50, 100, replace = TRUE)
df <- data.frame(vec)
而且您已经有了group 列,您可以创建labels 列。
library(dplyr)
library(ggplot2)
df %>%
mutate(group = ceiling(vec/10) * 10,
labels = paste(group-10, group, sep = '-')) -> df1
并在geom_histogram 中使用scale_x_continuous:
ggplot(df1) + aes(group) +
geom_histogram(bins = 5) +
scale_x_continuous(breaks = unique(df1$group), labels = unique(df1$labels))
【讨论】: