【问题标题】:Make geom_histogram display x-axis labels as integers instead of numerics使 geom_histogram 将 x 轴标签显示为整数而不是数字
【发布时间】:2023-03-23 06:10:01
【问题描述】:

我有一个data.frame,它包含多个组:

set.seed(1)
df <- data.frame(group = sample(c("a","b"),200,replace = T),
                 n = round(runif(200,1,2)))
df$n <- as.integer(df$n)

我正在尝试使用ggplot2geom_histogram 显示group 的直方图:

library(ggplot2)
ggplot(data = df, aes(x = n)) + geom_histogram() + facet_grid(~group) + theme_minimal()

知道如何让ggplot2 用直方图汇总的整数而不是当前显示的数值来标记 x 轴刻度吗?

【问题讨论】:

  • + scale_x_continuous(breaks = unique(df$n))

标签: r ggplot2 histogram axis-labels xticks


【解决方案1】:

您可以通过 geom_histogrambinwidth 参数来调整它:

library(ggplot2)
ggplot(data = df, aes(x = n)) + 
  geom_histogram(binwidth = 0.5) + 
  facet_grid(~group) + 
  theme_minimal()

另一个例子:

set.seed(1)
df <- data.frame(group = sample(c("a","b"),200,replace = T),
                 n = round(runif(200,1,5)))

library(ggplot2)
ggplot(data = df, aes(x = n)) + 
  geom_histogram(binwidth = 0.5) + 
  facet_grid(~group) + 
  theme_minimal()

【讨论】:

    【解决方案2】:

    您可以使用scale_x_continuous(breaks = seq(1, 2)) 手动指定中断。或者,您也可以分别设置中断和标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 2021-05-09
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2021-06-08
      相关资源
      最近更新 更多