本文介绍了如何在 ggplot2 中获得反向的 log10 比例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 ggplot2 绘制一个具有反向 log10 x 比例的图:

I'd like to make a plot with a reversed, log10 x scale using ggplot2:

require(ggplot2)
df <- data.frame(x=1:10, y=runif(10))
p <- ggplot(data=df, aes(x=x, y=y)) + geom_point() 

但是,我似乎可以使用 log10 比例反向比例:

However, it seems that I can either a log10 scale or a reversed scale:

p + scale_x_reverse() + scale_x_log10() 
p + scale_x_reverse()

我想这是合乎逻辑的,如果一个图层只能有一个比例.当然我可以通过自己对数据帧进行日志转换来破解它,df$xLog <- log10(df$x)但该解决方案似乎与 ggplot 的精神背道而驰.有没有办法在不进行 ggplot 调用外部的数据转换的情况下获得这种图?

I guess this is logical, if a layer can only have one scale. And certainly I could hack it by doing the log transform on the dataframe myself, df$xLog <- log10(df$x)but that solution is a seems contrary to the spirit of ggplot. Is there a way to get this kind of plot without doing data transformations external to the ggplot call?

推荐答案

@joran 在评论中给出的链接给出了正确的想法(构建您自己的转换),但对于新的 scales<ggplot2 现在使用的/code> 包.查看 scales 包中的 log_transreverse_trans 以获得指导和启发,可以制作一个 reverselog_trans 函数:

The link that @joran gave in his comment gives the right idea (build your own transform), but is outdated with regard to the new scales package that ggplot2 uses now. Looking at log_trans and reverse_trans in the scales package for guidance and inspiration, a reverselog_trans function can be made:

library("scales")
reverselog_trans <- function(base = exp(1)) {
    trans <- function(x) -log(x, base)
    inv <- function(x) base^(-x)
    trans_new(paste0("reverselog-", format(base)), trans, inv, 
              log_breaks(base = base), 
              domain = c(1e-100, Inf))
}

这可以简单地用作:

p + scale_x_continuous(trans=reverselog_trans(10))

给出了情节:

使用稍微不同的数据集来表明轴肯定是反转的:

Using a slightly different data set to show that the axis is definitely reversed:

DF <- data.frame(x=1:10,  y=1:10)
ggplot(DF, aes(x=x,y=y)) + 
  geom_point() +
  scale_x_continuous(trans=reverselog_trans(10))

这篇关于如何在 ggplot2 中获得反向的 log10 比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:52