R ggplot2:日志转换数据的自定义 y 轴刻度标签?
R ggplot2: custom y-axis tick labels for log-transformed data?
我见过的大多数处理转换基于日志的数据的教程都涉及使用基于日志的 y 轴或 x 轴刻度。如果我想绘制我的数据的基于 log10 的值并指示它们的相对实际基于指数的实际值:
library(ggplot2)
library(scales)
a <- c(5,10,15,20)
b <- c(100,210,350,750)
d <- log10(b)
test_df <- data.frame(xval = a,yval = d)
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
geom_point() +
scale_y_continuous(breaks = seq(1,3,by = 1),limits = c(1,3),labels = trans_format("log10",
math_format(10^.x)))
print(test_plt)
根据代码,我得到以下结果:
显然,R 正试图将已经 log10 转换的值再次转换为基于 log10 的值,有没有办法表示我希望我的 y 轴刻度值为 101、102、103等(即:绘制的值是 log10 转换的,但是 y-ticks 表示 log10 转换之前的实际值?还是我处理这个问题不正确?
您可以只使用 math_format()
及其默认参数:
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
geom_point() +
scale_y_continuous(breaks = seq(1,3,by = 1),
limits = c(1,3),
labels = math_format())
print(test_plt)
来自help("math_format")
:
Usage
... [Some content omitted]...
math_format(expr = 10^.x, format = force)
这正是您想要的格式,10^.x
,而不是10^.x
after a log10
转换,也就是你在 within trans_format("log10",
math_format(10^.x))
中调用它时得到的结果
我见过的大多数处理转换基于日志的数据的教程都涉及使用基于日志的 y 轴或 x 轴刻度。如果我想绘制我的数据的基于 log10 的值并指示它们的相对实际基于指数的实际值:
library(ggplot2)
library(scales)
a <- c(5,10,15,20)
b <- c(100,210,350,750)
d <- log10(b)
test_df <- data.frame(xval = a,yval = d)
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
geom_point() +
scale_y_continuous(breaks = seq(1,3,by = 1),limits = c(1,3),labels = trans_format("log10",
math_format(10^.x)))
print(test_plt)
根据代码,我得到以下结果:
显然,R 正试图将已经 log10 转换的值再次转换为基于 log10 的值,有没有办法表示我希望我的 y 轴刻度值为 101、102、103等(即:绘制的值是 log10 转换的,但是 y-ticks 表示 log10 转换之前的实际值?还是我处理这个问题不正确?
您可以只使用 math_format()
及其默认参数:
test_plt <- ggplot(data = test_df,aes(x = xval,y = yval)) +
geom_point() +
scale_y_continuous(breaks = seq(1,3,by = 1),
limits = c(1,3),
labels = math_format())
print(test_plt)
来自help("math_format")
:
Usage
... [Some content omitted]...
math_format(expr = 10^.x, format = force)
这正是您想要的格式,10^.x
,而不是10^.x
after a log10
转换,也就是你在 within trans_format("log10",
math_format(10^.x))