我有大约 10 个分类变量 - pay1、pay2、...、pay10,每个变量的值都是“是”或“否”。我想在图表上绘制每个变量的计数。例如 - 图表上的 bar1 应引用变量“pay1”,反映在“是”和“否”之间划分的观察总数(“是”在“否”之上,反之亦然)该方案应与图表上的所有 10 个变量。如果我能够为每个条显示“是”和“否”的百分比,那就更好了。有人可以帮忙吗?
TIA。
像这样编辑?
set.seed(1) # make reproducible
### 3x variables, 5x observations
df1 <- data.frame(x1=sample(c("yes","no"),5, replace=TRUE),
x2=sample(c("yes","no"),5, replace=TRUE),
x3=sample(c("yes","no"),5, replace=TRUE)
)
library(reshape2)
### convert to 'long form'
m1 <- melt(df1, measure.vars=c("x1","x2","x3"))
### now use facets to give one plot per variable
library(ggplot2)
qplot(variable, data=m1, fill=value) + facet_wrap( facets= ~variable, scale="free_x")
给予:
或者,如果您想要并排显示“是/否”,这对我来说看起来更好:
qplot(value, data=m1, fill=value) + facet_wrap( facets= ~variable, scale="free_x")
使用另一个答案中生成的数据框,这个怎么样?我认为您必须非常具体地了解您希望如何构建 x 轴才能在此处获得有用的答案。
set.seed(1) # make reproducible
### 3x variables, 5x observations
df1 <- data.frame(x1=sample(c("yes","no"),5, replace=TRUE),
x2=sample(c("yes","no"),5, replace=TRUE),
x3=sample(c("yes","no"),5, replace=TRUE)
)
library(reshape2)
m1 <- melt(df1, measure.vars=c("x1","x2","x3"))
m1[,"varval"]<-paste(m1$variable, m1$value, sep="-")
library(ggplot2)
# All counts now have a common x-axis:
varp<-ggplot(m1, aes(varv, fill=value))+geom_bar(stat="bin")
varp