[R] question on simple graph

Jim Lemon jim at bitwrit.com.au
Wed Feb 1 08:20:04 CET 2012


On 02/01/2012 08:13 AM, Rebecca Lisi wrote:
> I am having trouble generating a graph.
>
> I want to know the % of respondents who answered that they "strongly
> agree" or "agree" the "America owes R's ethnic group a better chance"
> (BTTRCHNC) and I want to organize it by racial group (RACESHRT).
>
> "BTTRCHNC" is organized ordinally from 1 through 5 with 1=Strongly
> Agree, 5=Strongly Disagree
> "RACESHRT" is ordinally organized from 1 through 5 where each number
> represents a racial group category, i.e. white, black, Asian, etc.
>
> Any hints for how to proceed?
>
Hi Rebecca,
Let's say you have 100 respondents who are members of five racial groups:

r_ethnic<-data.frame(BTTRCHNC=sample(1:5,100,TRUE),
  RACESHRT=sample(LETTERS[1:5],100,TRUE))
library(prettyR)
r_ethnic.xtab<-xtab(BTTRCHNC~RACESHRT,r_ethnic)
Crosstabulation of BTTRCHNC by RACESHRT
         RACESHRT
...     A       B       C       D       E
1       4       3       4       6       5       22
         18.18   13.64   18.18   27.27   22.73    -
         22.22   13.04   21.05   28.57   26.32   22

2       3       3       3       1       3       13
         23.08   23.08   23.08   7.69    23.08    -
         16.67   13.04   15.79   4.76    15.79   13

3       5       10      5       7       3       30
         16.67   33.33   16.67   23.33   10       -
         27.78   43.48   26.32   33.33   15.79   30

4       3       3       1       2       5       14
         21.43   21.43   7.14    14.29   35.71    -
         16.67   13.04   5.26    9.52    26.32   14

5       3       4       6       5       3       21
         14.29   19.05   28.57   23.81   14.29    -
         16.67   17.39   31.58   23.81   15.79   21

         18      23      19      21      19       100
         18      23      19      21      19       100

One way to illustrate this is to display a grouped bar plot of the 
percentages. First we'll have to recalculate the percentages:

r_ethnic.pct<-r_ethnic.xtab$counts
for(col in 1:dim(r_ethnic.xtab$counts)[2])
  r_ethnic.pct[,col]<-
   100*r_ethnic.xtab$counts[,col]/r_ethnic.xtab$col.margin[col]

Then use the resulting matrix to display the plot:

library(plotrix)
barp(r_ethnic.pct,names.arg=names(r_ethnic.xtab$col.margin),ylab="Percent",
  main="Percentages of options chosen by racial group",xlab="Racial group",
  col=c("#dddd00","#aadd44","#88dd88","#44ddaa","#00dddd"))
legend(3.5,44.5,
  c("Strongly agree","Agree","Neutral","Disagree","Strongly disagree"),
  fill=c("#dddd00","#aadd44","#88dd88","#44ddaa","#00dddd"))

You should get something like the attached PDF. There are other ways.

Jim
-------------- next part --------------
A non-text attachment was scrubbed...
Name: r_ethnic.pdf
Type: application/pdf
Size: 4983 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20120201/871f6a78/attachment.pdf>


More information about the R-help mailing list