首页 > 解决方案 > ggplot :在 X 轴上带有标准偏差的线图

问题描述

我正在尝试使用 ggplot 创建一个图,其中 X 轴是 X 变量的 +/-1 SD。我不确定这种人物叫什么或如何制作。我用 google 搜索了带有 SD 的 ggplot 线图,但没有发现任何类似的东西。任何建议将不胜感激。

在此处输入图像描述

更新:

这是可重现的代码,说明了我现在的位置:

library(tidyverse, ggplot2)
iris <- iris
iris <- iris %>% filter(Species == "virginica" | Species == "setosa")

ggplot(iris, aes(x=scale(Sepal.Length), y=Sepal.Width, group = Species, 
                       shape=Species, linetype=Species))+ 
  geom_line() + 
  labs(title="Iris Data Example",x="Sepal Length", y = "Sepal Width")+
  theme_bw()

在此处输入图像描述

我最初发布的图和这个图之间有两个主要区别:

A) 原始数字仅包含 +1 和 -1 SD,而我的示例包含 -1、0 +1 和 +2。

B) 原始图在 X 轴上具有 -1 和 +1 SD 的 Y 平均值,而我的示例中到处都有数据点。

标签: rggplot2figure

解决方案


R 中的scale函数减去均值并将结果除以标准差,这样所得变量可以解释为“与均值的标准差数”。另见维基百科

在 ggplot2 中,您可以在函数中动态包装您想要的scale()变量aes()

library(ggplot2)

ggplot(mpg, aes(scale(displ), cty)) +
  geom_point()

reprex 包于 2021-08-05 创建(v1.0.0)

编辑:

似乎我没有仔细阅读第一个数字的图例:似乎作者已经根据数据是否超过正标准差或负标准差对数据进行了分类。要以这种方式对数据进行分类,我们可以使用该cut函数。然后我们可以使用limitsscale 来排除(-1, 1]bin 并使用labels参数来制作更漂亮的轴标签。

相对于您的示例,我已经切换了 x 和 y 美学,否则其中一个物种在其中一个类别中没有任何观察结果。

library(tidyverse, ggplot2)
iris <- iris
iris <- iris %>% filter(Species == "virginica" | Species == "setosa")

ggplot(iris, 
       aes(x = cut(scale(Sepal.Width), breaks = c(-Inf, -1,1, Inf)), 
           y = Sepal.Length, group = Species, 
           shape = Species, linetype = Species))+ 
  geom_line(stat = "summary", fun = mean) + 
  scale_x_discrete(
    limits = c("(-Inf,-1]", "(1, Inf]"),
    labels = c("-1 SD", "+ 1SD")
  ) +
  labs(title="Iris Data Example",y="Sepal Length", x = "Sepal Width")+
  theme_bw()
#> Warning: Removed 73 rows containing non-finite values (stat_summary).

reprex 包于 2021-08-05 创建(v1.0.0)


推荐阅读