【问题标题】:ggplot2: Stat_function misbehaviour with log scalesggplot2:带有对数刻度的 Stat_function 不当行为
【发布时间】:2015-06-26 08:43:03
【问题描述】:

我正在尝试绘制对数标度的点直方图(用点而不是条形显示值的直方图)。结果应如下所示:


MWE:

让我们模拟一些数据:

set.seed(123)
d <- data.frame(x = rnorm(1000))

要得到点直方图我需要先计算直方图数据(hdata)

hdata <- hist(d$x, plot = FALSE)
tmp <- data.frame(mids = hdata$mids, 
                  density = hdata$density, 
                  counts = hdata$counts)

我们可以这样绘制

p <- ggplot(tmp, aes(x = mids, y = density)) + geom_point() + 
            stat_function(fun = dnorm, col = "red")
p

要得到这个图表:

理论上,我们应该能够应用对数刻度(并将 y 限制设置为高于 0),并且我们应该有与目标图相似的图片。

但是,如果我应用它,我会得到以下图表:

p + scale_y_log10(limits = c(0.001, 10))

stat_function 清楚地显示了非缩放值,而不是生成更接近第一张图片中实线的图形。

有什么想法吗?

奖金 有什么方法可以在不使用 hist(..., plot = FALSE) 函数的情况下用点绘制直方图?

编辑解决方法

一种可能的解决方案是在 ggplot 之外计算 dnorm-data,然后将其插入为一行。例如

tmp2 <- data.frame(mids = seq(from = min(tmp$mids), to = max(tmp$mids), 
                            by = (max(tmp$mids) - min(tmp$mids))/10000))
tmp2$dnorm <- dnorm(tmp2$mids) 

# Plot it
ggplot() + 
  geom_point(data = tmp, aes(x = mids, y = density)) + 
  geom_line(data = tmp2, aes(x = mids, y = dnorm), col = "red") + 
  scale_y_log10()

这将返回如下图。这基本上是图表,但它不能解决 stat_function 问题。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:
    library(ggplot2)
    set.seed(123)
    d <- data.frame(x = rnorm(1000))
    ggplot(d, aes(x)) +
      stat_bin(geom = "point", 
               aes(y = ..density..),
               #same breaks as function hist's default:
               breaks = pretty(range(d$x), n = nclass.Sturges(d$x), min.n = 1), 
               position = "identity") +
      stat_function(fun = dnorm, col = "red") +
      scale_y_log10(limits = c(0.001, 10))
    

    【讨论】:

      【解决方案2】:

      我在重新审视这个问题时发现的另一个可能的解决方案是将log10 应用于stat_function-调用。

      library(ggplot2)
      
      set.seed(123)
      d <- data.frame(x = rnorm(1000))
      
      hdata <- hist(d$x, plot = FALSE)
      tmp <- data.frame(mids = hdata$mids, 
                        density = hdata$density, 
                        counts = hdata$counts)
      
      ggplot(tmp, aes(x = mids, y = density)) + geom_point() + 
        stat_function(fun = function(x) log10(dnorm(x)), col = "red") +
        scale_y_log10()
      

      reprex package (v0.2.0) 于 2018 年 7 月 25 日创建。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多