问题描述
我觉得我缺少一些非常基本的东西,但是任何建议都值得赞赏。
我有一个包含19个变量的大型数据集,包括类别变量和数字变量。我想生成一个图表,其中三个变量(因为它们共享一个单位)平均且按因子排列。伪造样本数据:
Sex Low Freq High Freq Bandwidth
M 3000 4011 1011
M 3000 3600 600
M 2790 4237 1447
F 2700 3300 500
F 2900 4517 617
F 2813 3857 1044
我尝试过:
ggplot(TripleSongAverages,aes(x=factor(Sex),y='Low Freq','High Freq','Bandwidth')) + stat_summary(fun.y="mean",geom="bar")
解决方法
我建议使用tidyverse
方法重塑数据并计算平均值。这里的代码:
library(tidyverse)
#Data
df <- structure(list(Sex = c("M","M","F","F"),Low.Freq = c(3000,3000,2790,2700,2900,2813),High.Freq = c(4011,3600,4237,3300,4517,3857),Bandwidth = c(1011,600,1447,500,617,1044
)),class = "data.frame",row.names = c(NA,-6L))
代码:
#Reshape data and plot
df %>% pivot_longer(cols = -Sex) %>%
group_by(Sex,name) %>%
summarise(Mean=mean(value,na.rm=T)) %>%
#Plot
ggplot(aes(x=factor(Sex),y=Mean,fill=name)) +
geom_bar(stat='identity',position = position_dodge(0.9))
输出: