【问题标题】:specifying the format of tick labels in ggplot2 without a transform using scales?在不使用比例转换的情况下指定 ggplot2 中刻度标签的格式?
【发布时间】:2013-03-25 15:00:46
【问题描述】:

我在 ggplot2 中有一个图表(通过 rpy2),它在 log2 刻度上格式化 x 轴:

p += ggplot2.scale_x_continuous(trans=scales.log2_trans(),
                                   breaks=scales.trans_breaks("log2",
                                                              robj.r('function(x) 2^x'),
                                                              n=8),
                                   labels=scales.trans_format("log2", robj.r('math_format(2^.x)')))

如果 x 值已经在 log2 中,我怎样才能应用 scales 的格式转换,使值以 2^x 格式出现,而不是十进制 log2 值? IE。如果我要删除 trans= 参数,我怎样才能正确格式化刻度?

【问题讨论】:

  • 也许在trans_breaks 中用"identity" 替换"log2"?尽管只取消转换它们并让 ggplot 完成所有这些工作可能会更容易。

标签: r ggplot2 rpy2


【解决方案1】:

我可以用纯R给出答案,但我不知道rpy2能够翻译它。

实际上,您只需指定控制标签显示方式的labels 参数;不要更改transbreaks 参数,它们会影响整体缩放和出现中断的位置。以mtcars为例:

library("ggplot2")
library("scales")
ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  scale_x_continuous(labels = math_format(2^.x))

(显然这没有意义,因为重量还不是以 2 为底的对数刻度,但这个概念有效。)

【讨论】:

    【解决方案2】:

    猜测math_format()scales 中(现在无法检查),根据Brian 的回答,rpy2 版本应该如下:

    from rpy2.robjects.lib import ggplot2
    from rpy2.robjects.packages import importr
    scales = importr("scales")
    p = ggplot2.ggplot(mtcars) + \
            ggplot2.aes_string(x="wt", y="mpg")) + \ 
            ggplot2.geom_point() + \
            ggplot2.scale_x_continuous(labels = scales.math_format("2^.x"))
    p.plot()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2015-05-20
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多