用ggplot 2绘制对数尺度的负值 [英] Plot negative values in logarithmic scale with ggplot 2
问题描述
我需要使用ggplot2软件包在R图中绘制一些负值,使用x对数刻度。
例如我想用x绘制这些点对数比例 x <-c(-1,-10,-100)
y < - c( 1,2,3)
我知道R中负值的对数意味着NA值,但我需要这样的结果:点击查看图片
是否可以使用ggplot2?解析方案
有两个问题需要解决 - 计算log从负值开始,然后结合对数刻度和反转刻度。
要结合日志和反转比例,您可以使用@Briand Diggs提供的这是SO问题。
库(比例)
reverselog_t rans < - 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))
code b
为了使它适用于负值,请提供 x 值在 -x
中 ggplot()
调用,然后使用另一个转换为<$
scale_x_continuous()
来获取负值。
labels =
(x = c(-1,-10,-100),y = c(1,2,3))
ggplot(df, aes(-x,y))+ geom_point()+
scale_x_continuous(trans = reverselog_trans(base = 10),
labels = trans_format(identity,function(x)-x))
I need to plot with ggplot2 package in R a graph with some negative values using an x logarithmic scale.
For example I want to plot these points using an x logarithmic scale
x <- c(-1,-10,-100)
y <- c(1,2,3)
I know that the logarithm of a negative value in R pronuces a NA value, but I need a result like this:click to view the picture
Is it possible usign ggplot2?
There are two problems to solve - calculate log from negative values and then combine logarithmic scale and reverse scale.
To combine log and reverse scales you can use solution provided by @Briand Diggs on this SO question.
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))
}
To make it work with negative values, provide x
values as -x
in ggplot()
call and then use another transformation for labels=
inside scale_x_continuous()
to get back negative values.
df<-data.frame(x=c(-1,-10,-100),y= c(1,2,3))
ggplot(df,aes(-x,y))+geom_point()+
scale_x_continuous(trans=reverselog_trans(base=10),
labels=trans_format("identity", function(x) -x))
这篇关于用ggplot 2绘制对数尺度的负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!