【问题标题】:Replicate hist breaks in ggplot without a function outside of the plot在 ggplot 中复制 hist 中断,而没有绘图之外的功能
【发布时间】:2018-05-06 22:07:40
【问题描述】:

直方图中断

在基本图中,当您使用hist 函数时,它会使用nclass.Sturges 函数自动计算中断,但是在 ggplot 中,您必须提供中断。

如果我绘制经典 faithfull 数据的直方图,我会得到以下图表:

data("faithful")
hist(faithful$waiting)

这行得通

我发现在这个question,你可以模仿

library(tidyverse)
data("faithful")
brx <- pretty(range(faithful$waiting), n = nclass.Sturges(faithful$waiting), min.n = 1)
ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", breaks=brx)

但这不是

但我想在我的 ggplot 函数中添加中断,所以我尝试了这个:

ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", 
                 aes(breaks=pretty(range(waiting), 
                                   n = nclass.Sturges(waiting), 
                                   min.n = 1)))

这给了我以下错误:

Warning: Ignoring unknown aesthetics: breaks
Error: Aesthetics must be either length 1 or the same as the data (272): breaks, x

我明白它的意思,但是我可以把长度为a的美学放在aes中,例如:

ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", breaks=brx, 
                 aes(alpha = 0.5))

我做错了什么?

【问题讨论】:

  • 根据您的数据,brx 是长度为 13 的向量,而不是长度为 1。无论如何geom_histogram(使用与geom_bar 相同的美学)不理解breaks作为一种美学映射,所以即使像 aes(breaks = 1) 这样的东西也会被忽略。

标签: r ggplot2


【解决方案1】:

geom_histogram 根据文档使用与geom_bar 相同的aes,而breaks 不是这些美学之一。 (见geom_bar

在工作代码块中,您直接将中断传递给函数geom_histogram 并且有效,但在有问题的代码块中,您将其作为美学传递,而 ggplot 抱怨。

这对我有用,我认为你想要的:

ggplot(faithful, aes(x = waiting)) + 
geom_histogram(color = "darkgray", fill = "white", 
             breaks = pretty(range(faithful$waiting), 
                               n = nclass.Sturges(faithful$waiting), 
                               min.n = 1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 2016-09-13
    相关资源
    最近更新 更多