简体   繁体   English

如何在R中的图形上绘制多个类别变量?

[英]How do I plot a number of categorical variables on a graph in R?

I have about 10 categorical variables - pay1, pay2, ... , pay10 each having values either 'Yes' or 'No'. 我大约有10个类别变量-pay1,pay2,...,pay10,每个变量的值都是“是”或“否”。 I would like to plot the count of each of these variables on a graph. 我想在图表上绘制每个变量的计数。 For example - bar1 on the chart should refer to the variable 'pay1' reflecting the total number of observations divided between 'Yes' and 'No'('Yes' on top of 'No' or vice versa) This scheme should be consistent with all the 10 variables on the chart. 例如-图表上的bar1应该指向变量'pay1',该变量反映了观察结果总数,该观察结果分为“是”和“否”(“否”之上是“是”,反之亦然),该方案应与图表上的所有10个变量。 If I am able to display the percentage of 'Yes' and 'No' for each bar, even better. 如果我能够显示每个小节的“是”和“否”的百分比,那就更好了。 Would someone be able to help out on this? 有人可以帮忙吗?

TIA. TIA。

Edit Like this? 像这样编辑吗?

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")

giving: 赠送:

在此处输入图片说明

Or if you want the 'yes/no's side-by-side, which looks nicer to me: 或者,如果您想要并排显示“是/否”,这对我来说更好:

qplot(value, data=m1, fill=value) + facet_wrap( facets= ~variable, scale="free_x")

Using the data frame generated in the other answer, how about this? 使用另一个答案中生成的数据帧,如何处理? I think you have to be fairly specific about how you want your x-axis structured to get a useful answer here. 我认为您必须非常具体地说明您希望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

samplefrequencyplot.jpeg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM