英文:
R: Replacing X-Axis Logarithm Labels with Original Values
问题
我正在使用R编程语言。
我有以下的图表:
library(ggplot2)
df1 <- data.frame(x1 = rnorm(100, 100, 100))
df2 <- data.frame(x1 = rnorm(100, 1000, 1000))
df3 <- data.frame(x1 = rnorm(100, 10000, 10000))
df = data.frame(rbind(df1, df2, df3))
df$id = 1:nrow(df)
df$x1 = log(df$x1)
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_continuous(breaks = seq(0, 16, by = 1))
我的问题: 现在,我想将对数x轴标签替换为原始值 - 同时保留原始图表。
这是我的尝试:
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_continuous(breaks = seq(0, 16, by = 1),
labels = function(breaks) round(exp(breaks)))
请问有人能够教我如何做到这一点吗?
谢谢!
英文:
I am working with the R programming language.
I have the following graph:
library(ggplot2)
df1 <- data.frame(x1 = rnorm(100, 100, 100))
df2 <- data.frame(x1 = rnorm(100, 1000, 1000))
df3 <- data.frame(x1 = rnorm(100, 10000, 10000))
df = data.frame(rbind(df1,df2, df3))
df$id = 1:nrow(df)
df$x1 = log(df$x1)
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_continuous(breaks = seq(0, 16, by = 1))
My Question: Now, I am trying to replace the logarithm x-axis labels with the original values - while keeping the original graph.
Here is my attempt:
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_continuous(breaks = seq(0, 16, by = 1),
labels = function(breaks) round(exp(breaks)))
Can someone please show me how to do this?
Thanks!
答案1
得分: 1
你可以使用 scale_x_log10
。您需要对取对数的变量进行指数化处理(或者在第一次时不要对其取对数)
library(ggplot2)
set.seed(1)
df1 <- data.frame(x1 = rnorm(100, 100, 100))
df2 <- data.frame(x1 = rnorm(100, 1000, 1000))
df3 <- data.frame(x1 = rnorm(100, 10000, 10000))
df = data.frame(rbind(df1,df2, df3))
df$id = 1:nrow(df)
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_log10("x1", breaks = 10^(0:6))
请注意,无论您如何执行对数变换,小于或等于零的任何值都将变为 NaN
,因此将从图中移除。如果您想包括负值,可以使用伪对数变换:
ggplot(df, aes(x1)) +
geom_histogram(bins = 60) +
scale_x_continuous("x1", trans = "pseudo_log",
breaks = c(-(10^(1:6)), 0, 10^(1:6)))
英文:
You can use scale_x_log10
. You'll need to exponentiate the log-transformed variable (or just don't log it in the first place)
library(ggplot2)
set.seed(1)
df1 <- data.frame(x1 = rnorm(100, 100, 100))
df2 <- data.frame(x1 = rnorm(100, 1000, 1000))
df3 <- data.frame(x1 = rnorm(100, 10000, 10000))
df = data.frame(rbind(df1,df2, df3))
df$id = 1:nrow(df)
ggplot(df, aes(x1)) +
geom_histogram() +
scale_x_log10("x1", breaks = 10^(0:6))
Note that however you carry out the log transform, any values less than or equal to zero will be NaN
and therefore removed from the plot. If you want to include the negative values, you can use a pseudo-log transform instead:
ggplot(df, aes(x1)) +
geom_histogram(bins = 60) +
scale_x_continuous("x1", trans = "pseudo_log",
breaks = c(-(10^(1:6)), 0, 10^(1:6)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论