Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent results with plot in R

Tags:

plot

r

charts

I'm experimenting with plot in R and I'm trying to understand why it has the following behaviour.

I send a table into the plot function and it gives me a very nice variwidth graph which is quite insightful. However, after I reorder the columns of the table and send it to plot again, I get an odd scatter plot. What has happened in the re-ordering and how can I avoid this?

smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
colnames(smoke) <- c("High","Low","Middle")
rownames(smoke) <- c("current","former","never")
smoke <- as.table(smoke)
plot(smoke)  # This gives me a variwidth plot
smoke = smoke[,c("Low", "Middle", "High")] # I reorder the columns
plot(smoke)  # This gives me a weird scatter plot
like image 819
Dominic Soon Avatar asked Jan 13 '23 16:01

Dominic Soon


1 Answers

The way to investigate this is to do str() on the two instances of "smoke":

> str(smoke)
 table [1:3, 1:3] 51 92 68 43 28 22 22 21 9
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "current" "former" "never"
  ..$ : chr [1:3] "High" "Low" "Middle"

> str( smoke[,c("Low", "Middle", "High")] )
 num [1:3, 1:3] 43 28 22 22 21 9 51 92 68
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "current" "former" "never"
  ..$ : chr [1:3] "Low" "Middle" "High"

The first one is a table object whereas the second on is a matrix. You could also have done class() on both and gotten somewhat more compact answer. To understand why this is important also look at

methods(plot) 

.... and see that there is a plot.table* method. The '*' indicates that it is not "visible" and that were you needing to see the code that you would need to use:

getAnywhere(plot.table)

As Ananda has shown, you can restore the table class to that smoke object and then get the dispatch system to send the object to plot.table*.

like image 53
IRTFM Avatar answered Jan 19 '23 11:01

IRTFM