如何在ggplot2中获得反转的log10比例? [英] How to get a reversed, log10 scale in ggplot2?

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

问题描述

  require(ggplot2)$(ggplot2)$我想用一个反转的,使用ggplot2的log10 x scale进行绘图: (x = 1,10,y = runif(10))
p <-ggplot(data = df,aes(x = x,y = y))+ geom_point ()

但是,我可以 log10比例反转比例:

  p + scale_x_reverse()+ scale_x_log10()
code>

  p + scale_x_reverse()



我想这是合乎逻辑的,如果一个图层只能有一个比例。当然,我可以通过在数据框上进行日志转换来破解它, df $ xLog < - log10(df $ x)
,但该解决方案是似乎违背ggplot的精神。有没有办法得到这种情节,而无需在ggplot调用之外进行数据转换?

@joran在他的评论中给出了正确的想法(构建自己的变换),但是对于 ggplot2 的新 scale $ c>现在使用。在尺度包中查看 log_trans reverse_trans 以获得指导和灵感,a reverselog_trans <

$ p $ lt; code> library(scales)
reverselog_trans< - function( base = exp(1)){
trans < - function(x)-log(x,base)
inv < - function(x)base ^( - x)
trans_new (paste0(reverseelog-,format(base)),trans,inv,
log_breaks(base = base),
domain = c(1e-100,Inf))
}

可以简单地使用它:

  p + scale_x_continuous(trans = reverselog_trans(10))

其中给出的情节:





使用稍微不同的数据集来显示该轴肯定是相反的:

  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))


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() 

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()

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?

解决方案

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))
}

This can be used simply as:

p + scale_x_continuous(trans=reverselog_trans(10))

which gives the plot:

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比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆