[英]How to plot histogram with means calculated by factor levels from multiple columns
我是R的新手,可能是我的問題看起來很傻,我花了一半的時間獨自嘗試自己解決問題,但沒有運氣。 我沒有找到說明該操作方法的教程,如果您知道這樣的教程,也歡迎您。 我想繪制直方圖,其均值由列中的因子計算得出。 我的初始數據如下所示(簡化版):
code_group scale1 scale2
1 5 3
2 3 2
3 5 2
因此,我需要直方圖,其中每個由code_group着色的bean及其值是code_group,x軸上帶有scale1和scale2標簽的每個級別的平均值。 每個標簽包含三個bean(用於三個級別的factor code_group)。 我設法自己計算了每個級別的均值,如下所示:
code_group scale1 scale2
1 -1.0270270 0.05405405
2 -1.0882353 0.14705882
3 -0.7931034 -0.34482759
但我不知道如何將其繪制在historgam中! 提前致謝!
假設您指的是條形圖而不是直方圖 (如果不是這種情況,請澄清您的問題),您可以melt
數據並使用ggplot
將其ggplot
如下:
library(ggplot2)
library(reshape2)
##
mdf <- melt(
df,
id.vars="code_group",
variable.name="scale_type",
value.name="mean_value")
##
R> ggplot(
mdf,
aes(x=scale_type,
y=mean_value,
fill=factor(code_group)))+
geom_bar(stat="identity",position="dodge")
數據:
df <- read.table(
text="code_group scale1 scale2
1 -1.0270270 0.05405405
2 -1.0882353 0.14705882
3 -0.7931034 -0.34482759",
header=TRUE)
編輯:
您可以像下面那樣對數據本身(或其副本)進行修改:
mdf2 <- mdf
mdf2$code_group <- factor(
mdf2$code_group,
levels=1:3,
labels=c("neutral",
"likers",
"lovers"))
names(mdf2)[1] <- "group"
##
ggplot(
mdf2,
aes(x=scale_type,
y=mean_value,
fill=group))+
geom_bar(stat="identity",position="dodge")
##
給定您提供的平均值,您可以執行以下操作:
重新創建簡化的數據集:
d=data.frame(code_group=c(1,2,3),scale1=c(-1.02,-1.08,-0.79),scale2=c(0.05,.15,-0.34))
創建圖形:
barplot(c(d[,'scale1'],d[,'scale2']),col=d[,'code_group'],names.arg=c(paste('scale1',unique(d[,'code_group']),sep='_'),paste('scale2',unique(d[,'code_group']),sep='_')))
這將為您提供以下圖形:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.