ggplot2 — 有什么方法可以自动在同一个散点图上绘制不同的 transformed-y 坐标吗?

ggplot2 — any way to automatically plot the different transformed-y on the same scatter plot, for you?

问:给定一个使用 ggplot() 的典型 x,y 散点图,ggplot2 能否自动绘制变换后的 y 值?

Example: simple x,y scatter

• 在此示例中,使用 ggplot2 中的 stat_smooth(..) 功能进行多次 lm 拟合:

ggplot(df, aes(x=myX, y=myY)) +
geom_point(color=‘darkgray’) + 
   stat_smooth(method=‘lm’, se=F, aes(color=‘black’), formula=“y ~ x”) +
   stat_smooth(method=‘lm’, se=F, aes(color=‘blue’), formula=“log(y) ~ x”) +
   stat_smooth(method=‘lm’, se=F, aes(color=‘green’), formula=“sqrt(y) ~ x”) +

   # log-scale it so transforms show up:
   scale_y_continuous(trans=‘log10’)

• 但我还想绘制变换后的 y 的散点图:sqrt(y)log(y)

  1. ggplot2 是否具有将这些绘制到同一图中的自动功能?

  2. 如果不是,最简单的推荐方法是什么?是手动计算然后 unstack (base-R) 还是 melt (reshaper2) 它们变成长格式?

我建议采用下一种方法。您可以在新变量中创建转换。然后,将数据重塑为长数据,然后对所有变量或方面使用一种可视化方式进行绘图。这里的方面方法:

library(tidyverse)
#Code1
iris %>% mutate(x=Petal.Length,y=Sepal.Length,logy=log(Sepal.Length),sqrty=sqrt(Sepal.Length)) %>%
  select(c(x,y,logy,sqrty)) %>%
  pivot_longer(-x) %>%
  ggplot(aes(x=x,y=value,color=name,group=name))+
  geom_point()+
  geom_smooth(method = lm,se=F)+
  facet_wrap(.~name,scales = 'free_y')

输出:

或者个别剧情的做法:

#Code2
iris %>% mutate(x=Petal.Length,y=Sepal.Length,logy=log(Sepal.Length),sqrty=sqrt(Sepal.Length)) %>%
  select(c(x,y,logy,sqrty)) %>%
  pivot_longer(-x) %>%
  ggplot(aes(x=x,y=value,color=name,group=name))+
  geom_point()+
  geom_smooth(method = lm,se=F)

输出:

我使用了 iris 数据集和 tidyverse 函数。