我需要ggplot scale_x_log10()为我提供负数和正数作为输出 [英] I need ggplot scale_x_log10() to give me both negative and positive numbers as output

查看:272
本文介绍了我需要ggplot scale_x_log10()为我提供负数和正数作为输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里生成带有正数和负数的精细直方图.

I generate a fine histogram here with both positive and negative numbers.

x <- rnorm(5000,0,1000)
library(ggplot2)
df <- data.frame(x)
ggplot(df, aes(x = x)) + geom_histogram()

我想要的是记录一个x轴.当我使用scale_x_log10()仅对正数执行此操作时,它就像一个符咒.但是这里并没有,或者删除了我的负数,然后将它们添加到正数.

What I want is to have a logged x-axis. When I do this for only positive numbers with scale_x_log10(), it works like a charm. But here it does not and it either removes my negative numbers are adds them to the positive numbers.

ggplot(df, aes(x = x)) + geom_histogram() + scale_x_log10()

我真正想要的是刻度线和刻度线之间的间距遵循对数模式,并且x轴上0的任一侧都是彼此的镜像,但我似乎无法理解.

All I really want is for the ticks and the spacing between the ticks to follow the log pattern and for either side of 0 on the x-axis to be mirror images of each other but I cannot seem to get that.

推荐答案

这可以通过定义新的转换来实现(签名日志",sign(x)*log(abs(x))中具有负"对数标度的-in-r>直方图可能更原则,或者是上面评论中建议的带符号平方根),但是我怀疑这是否是一个好主意.不过……(教一个人钓鱼,你一辈子给他喂食;给他一根绳子,他就可以自己上吊……")……你可以通过trans_new定义自己的轴转换为如下所示.

This is possible to do by defining a new transformation (a "signed log", sign(x)*log(abs(x)); the asinh transformation suggested by Histogram with "negative" logarithmic scale in R might be more principled, or a signed square root as suggested in the comments above), but I question whether it's a good idea or not. Nevertheless ... ("Teach a man to fish and you feed him for a lifetime; give him a rope, and he can go hang himself ...") ... you can define your own axis transformations via trans_new as shown below.

设置:

library(ggplot2); theme_set(theme_bw())
set.seed(101)
df <- data.frame(x=rnorm(5000,0,1000))

设置新的转换:

weird <- scales::trans_new("signed_log",
       transform=function(x) sign(x)*log(abs(x)),
       inverse=function(x) sign(x)*exp(abs(x)))

尝试一下-首先了解原始点:

Try it out -- first on the raw points:

ggplot(df,aes(x,x))+geom_point()+
    scale_y_continuous(trans=weird)

现在在直方图上:

ggplot(df, aes(x = x)) + geom_histogram()+
    scale_x_continuous(trans=weird)

您应该担心的事情:

  • 当值介于-1和1之间时,这种转换将变得毫无意义
  • 您可能需要担心在不适当缩放bin高度的情况下变换直方图的轴:这可能会给您造成对概率密度的误导印象-尽管在这种情况下,ggplot(df, aes(x = weird$transform(x))) + geom_histogram()看起来与上面的图大致相同. ..
  • this transformation is going to be nonsensical when you have values between -1 and 1
  • you might have to worry about transforming the axis of a histogram without scaling bin height appropriately: it may give you a misleading impression of the probability density -- although in this case ggplot(df, aes(x = weird$transform(x))) + geom_histogram() looks about the same as the plot above ...

这篇关于我需要ggplot scale_x_log10()为我提供负数和正数作为输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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