简体   繁体   中英

plot of categorical variables with R

I'm a newcomer both to R and statistics in general. I'm trying to plot the relationship of two categorical variables which are vectors of length 147. The tables for each are:

    AgeGroup
26-49   50-64   65 and over  Under 26
101     16      5            25

and

    Role
A/C     C/H                     Dietician
6       8                       2
Doctor  Healthcare Assistant    Lab
56      7                       2
Nurse   Pharmacist              Phlebotomist
54      5                       1
Radiographer                    Therapist
1                               5

After reading an answer to a question here from 2012 I expected to get a spineplot by using this command:

    plot(mydata$Role,mydata$AgeGroup,xlab="Role",ylab="Age Group")

but it returns:

    Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
5: In min(x) : no non-missing arguments to min; returning Inf
6: In max(x) : no non-missing arguments to max; returning -Inf

I'm guessing that Warning message 1 is telling me that xycoords() is attempting to coerce the categorial elements into numeric data and when it fails to do so is returning NAs, which gives plot() nothing to work with.
In short, what am I failing to understand and how do I fix it?

I guess I might as well put my comments in an answer:

There is a plot.table method so why not try:with( mydata, plot( table(Role, AgeGroup), xlab="Role",ylab="Age Group") – BondedDust 3 hours ago

with creates a local environment where the column names are interpreted as objects, and within that environment, a 'table'-object is passed to plot . The plot function is generic (try typing methods(plot) ) so it looks up the proper method for the 'table'-classed object and does its work. To see the code for plot.table which is not exported, you need to use getAnywhere(plot.table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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