gpt4 book ai didi

r - 使用 ggplot 2 以对数刻度绘制负值

转载 作者:行者123 更新时间:2023-12-02 08:36:22 24 4
gpt4 key购买 nike

我需要在 R 中使用 ggplot2 包绘制带有一些负值的图形,使用 x 对数刻度。
例如,我想使用 x 对数刻度绘制这些点

x <- c(-1,-10,-100)
y <- c(1,2,3)
我知道 R 中负值的对数产生 NA 值,但我需要这样的结果:
click to view the picture
这可以使用ggplot2吗?

最佳答案

有两个问题需要解决 - 从负值计算对数,然后结合对数标度和反向标度。

要结合对数和反向比例,您可以使用@Briand Diggs 在 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))
}

要使其适用于负值,请提供 x值为 -xggplot()调用然后对 labels= 使用另一个转换内 scale_x_continuous()取回负值。
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))

enter image description here

关于r - 使用 ggplot 2 以对数刻度绘制负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com