[R] dotchart for matrix data

David Winsemius dwinsemius at comcast.net
Sat Dec 18 15:01:21 CET 2010


On Dec 18, 2010, at 7:01 AM, e-letter wrote:

> Readers,
>
> I am trying to use the function dotchart. The data is:
>
>> testdot
>  category values1 values2 values3 values4
> 1        a      10      27      56     709
> 2        b       4      46      47     208
> 3        c       5      17      18     109
> 4        d       6      50      49     308
>
> The following error occurs
>
>> dotchart(testdot,groups=testdot[,2])
> Error in dotchart(testdot, labels = testdot[, 1], groups = testdot[,  
> 2]) :
>        'x' must be a numeric vector or matrix
>
> According to my understanding (clearly wrong!) of the documentation
> for dotchart (accessed from the manual in section 'graphics'), columns
> of data can be selected by 'groups' for subsequent plotting.

The misunderstanding is in how you see the grouping information versus  
how R expects it. R generally expects such data in what is called  
"long" format, i.e. there will be one values columns and a category  
column. There are various ways to change the arrangement of your data.  
The function stack(), the function reshape(), or probably most  
commonly the function melt from reshape2 being the typical chosen  
routes.

> The
> objective is to be able to create a dot chart where each row is
> labelled according to the row names in the 'category' column and two
> columns can be selected, e.g. 'values1' and 'values2'. Then I tried:
>
>> testdot1<-testdot[,1]
>> testdot2<-testdot[,2]
>> testdot3<-testdot[,3]
>> dotchart(c(testdot2,testdot3),labels=testdot1)

See if this is more to your liking:

require(reshape)   # I'm not sure why I have reshape_0.8.3 rather than  
reshape2 loaded
                    # I'm pretty sure Hadley would prefer that people  
use pkg:reshape2
  mdot <- melt(dot)
dotchart(mdot$value, groups=mdot$category, labels=mdot$variable)
# OR more readable
with(mdot, dotchart(value, groups=category, labels=variable)  )

I'm not sure I got the roles of "values" and "category" correct, but  
it should be a simple matter to switch them in the dotcghart call if  
that is your pleasuRe.


>
> A graph is produced, but not as expected. Instead of 4 rows labelled
> (descending order from top row) a,b,c,d, and each row containing two
> data points, the graph shows 8 rows (?) with the top 4 rows
> un-labelled and the bottom 4 rows labelled (descending order) d,c,b,a
> and each row shows only 1 datum point.
>
> How do I specify the order of labelling of the rows?
> How do I write correct commands to obtain a dot chart with 4 rows,
> each row containing the two (or if required three) data points?

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list