我有以下问题:我想在一个框图上可视化离散和连续变量,其中后者具有一些极高的值。这使BoxPlot毫无意义(图表的“点”甚至“正文”太小),这就是为什么我想在log10刻度上显示此内容的原因。我知道我可以从可视化中省略极端价值,但我并非打算。

让我们看看一个带有钻石数据的简单示例:

m <- ggplot(diamonds, aes(y = price, x = color))

alt text

这个问题在这里并不严重,但我希望您能想象为什么我想在log10量表上看到这些值。让我们尝试一下:

m + geom_boxplot() + coord_trans(y = "log10")

alt text

如您所见,Y轴是log10缩放的,看起来不错,但是X轴存在问题,这使该图非常奇怪。

问题没有发生 scale_log, , 但 这不是我的选择, ,因为我不能以这种方式使用自定义格式化器。例如:

m + geom_boxplot() + scale_y_log10() 

alt text

我的问题:有人知道一个解决方案以绘制boxplot用log10刻度上的y轴上的框架图,该标签可以用a自由格式化 formatter 在此功能 线?


编辑问题以根据答案和评论来帮助答案:

我真正追求的是:一个log10不用科学标签转换了轴(y)。我想标记它像美元 (formatter=dollar) 或任何自定义格式。

如果我尝试 @Hadley的建议,我会收到以下警告:

> m + geom_boxplot() + scale_y_log10(formatter=dollar)
Warning messages:
1: In max(x) : no non-missing arguments to max; returning -Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

带有不变的Y轴标签:

alt text

有帮助吗?

解决方案

最简单的是只给“ trans”(以前是'formatter'参数log函数的名称:

m + geom_boxplot() + scale_y_continuous(trans='log10')

编辑:或者,如果您不喜欢这样,那么其中的任何一个似乎都会给出不同但有用的结果:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2&3:进一步的实验(丢弃试图成功将“ $”标志放在记录值面前的一个试图将“ $”标志的一个实验):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

注意在有关包装语法更改的评论中添加了2017年中期:

scale_y_continouul(formatter ='log10')现在是scale_y_continouul(trans ='log10')(ggplot2 v2.2.1)

其他提示

我也有类似的问题,这个量表对我来说像魅力一样有用:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

如您所需的中间级别(10^3.5),您需要调整格式:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

执行::

enter image description here

使用的另一个解决方案 scale_y_log10trans_breaks, trans_formatannotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

我想我终于通过在可视化之前对数据进行了一些手动转换来理解:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

并制定一个格式化器以后来计算“对数数据”:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

并用给定的格式绘制图:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

抱歉,社区打扰您以前可以解决的问题!有趣的部分是:我正在努力使这个情节工作一个月前,但没有成功。在这里询问之后,我明白了。

无论如何,感谢@dwin的动力!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top