Plot negative values in logarithmic scale with ggplot 2

痞子三分冷 提交于 2019-11-30 19:05:30

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/20924705/plot-negative-values-in-logarithmic-scale-with-ggplot-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!