R ggplot2:使用 stat_summary(平均值)和对数刻度 [英] R ggplot2: using stat_summary (mean) and logarithmic scale
问题描述
随着时间的推移,我有一堆测量值,我想在 R 中绘制它们.这是我的数据示例.我有 4 个时间点中的每一个的 6 个测量值:
I have a bunch of measurements over time and I want to plot them in R. Here is a sample of my data. I've got 6 measurements for each of 4 time points:
values <- c (1012.0, 1644.9, 837.0, 1200.9, 1652.0, 981.5,
2236.9, 1697.5, 2087.7, 1500.8,
2789.3, 1502.9, 2051.3, 3070.7, 3105.4,
2692.5, 1488.5, 1978.1, 1925.4, 1524.3,
2772.0, 1355.3, 2632.4, 2600.1)
time <- factor (rep (c(0, 12, 24, 72), c(6, 6, 6, 6)))
这些数据的规模是任意的,实际上我将对其进行标准化,以便 t=0 的平均值为 1.
The scale of these data is arbitrary, and in fact I'm going to normalize it so that the average of t=0 is 1.
norm <- values / mean (values[time == 0])
到目前为止一切顺利.使用 ggplot
,我绘制了各个点以及穿过每个时间点平均值的线:
So far so good. Using ggplot
, I plot both the individual points, as well as a line that goes through the average at each time point:
require (ggplot2)
p <- ggplot(data = data.frame(time, norm), mapping = aes (x = time, y = norm)) +
stat_summary (fun.y = mean, geom="line", mapping = aes (group = 1)) +
geom_point()
然而,现在我想应用对数刻度,这就是我的麻烦开始的地方.当我这样做时:
However, now I want to apply a logarithmic scale, and this is where my trouble starts. When I do:
q <- ggplot(data = data.frame(time, norm), mapping = aes (x = time, y = norm)) +
stat_summary (fun.y = mean, geom="line", mapping = aes (group = 1)) +
geom_point() +
scale_y_log2()
该线在 t=0 时不会像您期望的那样通过 0,因为 log (1) == 0.相反,该线与 y 轴的交叉点略低于 0.显然,ggplot
在对数转换之后应用平均值,这给出了不同的结果.我希望它取平均值 before 对数转换.
The line does NOT go through 0 at t=0, as you would expect because log (1) == 0. Instead the line crosses the y-axis slightly below 0. Apparently, ggplot
applies the mean after log transformation, which gives a different result. I want it to take the mean before log transformation.
如何告诉 ggplot
先应用平均值?有没有更好的方法来创建这个图表?
How can I tell ggplot
to apply the mean first? Is there a better way to create this chart?
推荐答案
scale_y_log2()
会先做转换,然后计算几何.
scale_y_log2()
will do the transformation first and then calculate the geoms.
coord_trans()
将做相反的事情:首先计算几何图形,然后变换轴.
coord_trans()
will do the opposite: calculate the geoms first, and the transform the axis.
所以你需要 coord_trans(ytrans = "log2")
而不是 scale_y_log2()
So you need coord_trans(ytrans = "log2")
instead of scale_y_log2()
这篇关于R ggplot2:使用 stat_summary(平均值)和对数刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!