我正在尝试创建一个条形图网格,以显示不同物种的平均值。我正在使用iris
这个问题的数据集。
我汇总了数据,将其长期分解为长格式,然后尝试使用facet_wrap
。
iris %>%
group_by(Species) %>%
summarise(M.Sepal.Length=mean(Sepal.Length),
M.Sepal.Width=mean(Sepal.Width),
M.Petal.Length= mean(Petal.Length),
M.Petal.Width=mean(Petal.Width)) %>%
gather(key = Part, value = Value, M.Sepal.Length:M.Petal.Width) %>%
ggplot(., aes(Part, Value, group = Species, fill=Species)) +
geom_col(position = "dodge") +
facet_grid(cols=vars(Part)) +
facet_grid(cols = vars(Part))
但是,我得到的图形具有x.axis标签,这些标签串在每个构面网格上。此外,聚簇图不在每个构面框中居中。相反,它们出现在各自x轴标签的位置。我想摆脱x轴标签,将图形居中,并在每个构面内缩放图形。
这是用我的预期输出标记的结果图的图像:
也许这就是您要找的东西?
关键更改是:
Part
作为映射到的变量,以x
这种方式将数据绘制在每个方面的相同位置facet_wrap
以便可以使用scales = "free_y"
labs
手动添加X标题theme
以消除x轴刻度和刻度标签。library(ggplot2)
library(dplyr) # Version >= 1.0.0
iris %>%
group_by(Species) %>%
summarise(across(1:4, mean, .names = "M.{col}")) %>%
gather(key = Part, value = Value, M.Sepal.Length:M.Petal.Width) %>%
ggplot(., aes(x = 1, y = Value, group = Species, fill=Species)) +
geom_col(position = "dodge") +
facet_wrap(.~Part, nrow = 1, scales = "free_y") +
labs(x = "Part") +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank())
我还自由地将您的手动呼叫切换summarise
为新across
功能。
您也可以按照以下方法计算误差线:
library(tidyr)
iris %>%
group_by(Species) %>%
summarise(across(1:4, list(M = mean, SE = ~ sd(.)/sqrt(length(.))),
.names = "{fn}_{col}")) %>%
pivot_longer(-Species, names_to = c(".value","Part"),
names_pattern = "([SEM]+)_(.+)") %>%
ggplot(., aes(x = 1, y = M, group = Species, fill=Species)) +
geom_col(position = "dodge") +
geom_errorbar(aes(ymin = M - SE, ymax = M + SE), width = 0.5,
position = position_dodge(0.9)) +
facet_wrap(.~Part, nrow = 1, scales = "free_y") +
labs(x = "Part", y = "Value") +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句