Dominic Soon
Dominic Soon

Reputation: 41

Inconsistent results with plot in R

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

Upvotes: 4

Views: 109

Answers (2)

IRTFM
IRTFM

Reputation: 263332

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*.

Upvotes: 5

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

When you reordered the columns, you changed the class of "smoke" from "table" to "matrix", so plot, which returns different default results depending on its input, returned a different plot.

Try:

plot(as.table(smoke))

Upvotes: 4

Related Questions