如何在R中的图上绘制多个分类变量? [英] How do I plot a number of categorical variables on a graph in R?

查看:635
本文介绍了如何在R中的图上绘制多个分类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约10个分类变量 - 支付1,支付2,...,支付10,每个支付的值都是'是'或'否'。
我想在图表上绘制每个变量的数量。
例如 - 图表上的bar1应该指代变量'pay1',它反映了在'是'和'否'之间划分的观测总数('否'或反之亦然'是')
此方案应与图表中的所有10个变量一致。如果我能够显示每个栏的是和否的百分比,甚至更好。
有人可以帮忙吗?

TIA。

解决方案 / b> $ p
$ b

  set.seed(1)#make reproducible 
### 3x变量,5x观察值
df1 < - data.frame(x1 = sample(c(yes,no),5,replace = TRUE),
x2 = sample(c(是,no),5,replace = TRUE),
x3 = sample(c(yes,no),5,replace = TRUE)

library(reshape2)
###转换为'长格式'
m1 < - melt(df1,measure.vars = c(x1,x2, x3))
###现在使用构面给每个变量绘制一个绘图
library(ggplot2)
qplot(variable,data = m1,fill = value)+ facet_wrap(facets =〜变量,scale =free_x)

给出:



或者如果你想要'是/否'并排,这对我来说更好看:

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


I have about 10 categorical variables - pay1, pay2, ... , pay10 each having values either 'Yes' or 'No'. 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. 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.

解决方案

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

这篇关于如何在R中的图上绘制多个分类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆