[英]Plot negative values in logarithmic scale with ggplot 2
我需要在 R 中使用 ggplot2 包繪制帶有一些負值的圖形,使用 x 對數刻度。
例如,我想使用 x 對數刻度繪制這些點
x <- c(-1,-10,-100)
y <- c(1,2,3)
我知道 R 中負值的對數產生 NA 值,但我需要這樣的結果:
這可以使用ggplot2嗎?
有兩個問題需要解決 - 從負值計算對數,然后結合對數標度和反向標度。
要結合對數和反向比例,您可以使用 @Briand Diggs 在這個 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))
}
要使其適用於負值,請在ggplot()
調用ggplot()
x
值作為-x
提供,然后在scale_x_continuous()
內對labels=
使用另一個轉換來取回負值。
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))
為此,我發現ggallin
包中的pseudolog10_trans
轉換非常有用,因為它可以在對數尺度上同時容納正數和負數的情況。 例如
library(ggplot2)
library(ggallin)
x <- c(-1,-10,-100, 1, 10, 100)
y <- c(1,2,3, 1,2,3)
df = data.frame(x = x, y = y)
My_Plot = ggplot(
df,
aes(x=x, y=y)) +
geom_point() +
scale_x_continuous(trans = pseudolog10_trans)
My_Plot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.