r - 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 平均值,而我的示例中到处都有数据点。
解决方案
R 中的scale
函数减去均值并将结果除以标准差,这样所得变量可以解释为“与均值的标准差数”。另见维基百科。
在 ggplot2 中,您可以在函数中动态包装您想要的scale()
变量aes()
。
library(ggplot2)
ggplot(mpg, aes(scale(displ), cty)) +
geom_point()
由reprex 包于 2021-08-05 创建(v1.0.0)
编辑:
似乎我没有仔细阅读第一个数字的图例:似乎作者已经根据数据是否超过正标准差或负标准差对数据进行了分类。要以这种方式对数据进行分类,我们可以使用该cut
函数。然后我们可以使用limits
scale 来排除(-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)
推荐阅读
- php - Laravel orWherehas 过滤多列关系
- r - R bslib 更改导航栏颜色引导版本 5
- javascript - 使用参数访问网站时出现404错误(vuejs)
- javascript - JS - 正则表达式适用于 regex101 但不适用于我的节点脚本
- dnssec - 如何启用 SSHFP?
- apache-kafka - Confluent Operator 添加额外的连接器
- javascript - 为什么 array.map 嵌套在 array.forEach 中(在这种情况下)比其他方式快得多?
- c++ - LLVM | 插入带有 uintptr_t 参数的钩子函数
- python - Python3 argp 对于从终端传递并在配置中传递的字符串的不同行为
- java - 允许保留阻止以解除对一种以上代理类型的阻止