【问题标题】:How does ggplot calculate its default breaks?ggplot 如何计算其默认休息时间?
【发布时间】:2016-11-23 23:25:28
【问题描述】:

标题相对不言自明。我想知道 ggplot 如何决定它的默认中断(以及标签)。

从下面的代码看来,每个geom的方法都是一样的:

library(ggplot2)

ggplot(data=mtcars,mapping=aes(x=carb,y=hp,fill=as.factor(gear)))+
  geom_bar(stat="identity",position="dodge")

ggplot(data=mtcars,mapping=aes(x=carb,y=hp,fill=as.factor(gear)))+
  geom_point()

任何帮助将不胜感激

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我自己也有同样的问题,Google 把我带到了这个 SO 问题,所以我想我会做一些挖掘工作。

    假设我们绘制

    library(ggplot2)
    ggplot(mtcars, aes(x = cyl, y = mpg, size = hp)) +
      geom_point() 
    

    这给了我们下面的情节,我们想知道mpg (10, 15, ..., 35), cyl (4, 5, ..., 8) 和派生出hp (100, 150, ..., 300)。

    关注mpg,我们检查scale_y_continuous 的代码,发现它调用了continuous_scale。然后,调用?continuous_scale,我们看到,在trans 参数的描述下,

    一个转换对象将一个转换、它的逆转换以及用于生成中断和标签的方法捆绑在一起。

    然后,查找?scales::trans_new,我们看到breaks 参数的默认值为extended_breaks()。顺着线索,我们发现scales::extended_breaks 调用labeling::extended(rng[1], rng[2], n, only.loose = FALSE, ...)。将此应用于我们的数据,

    with(mtcars, labeling::extended(range(mpg)[1], range(mpg)[2], m = 5))
    # [1] 10 15 20 25 30 35
    

    这是我们在情节中观察到的。这提出了为什么,尽管

    with(mtcars, labeling::extended(range(hp)[1], range(hp)[2], m = 5))
    # [1]  50 100 150 200 250 300 350
    

    我们没有在图例中观察到 50 和 350。我的理解是答案与https://stackoverflow.com/a/13888731/6455166有关。

    【讨论】:

    • 伟大的挖掘。题外话:如果你想设置 y 中断的数量等于 x 中断的数量,为了对称,你可以这样做:xbreaks <- ggplot_build(p)$layout$panel_ranges[[1]]$x.major_source 提取中断,然后在你的 ggplot 中使用它们:p <- p + scale_y_continuous(breaks = xbreaks)
    • 我还发现extended()s 选项非常有用,尽管文档基本上只是“rtfa”。 Q,“一组不错的数字”对我来说非常有效,可以以分钟和小时为单位来衡量持续时间,即使用 c(15, 20, 30, 60) - 所以规模适当地试图让我在这些分钟标记处休息。
    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 2011-04-29
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多