Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricks to override plot.factor?

Tags:

plot

r

I've been using plot for quite awhile now and I'm wondering how much would be broken if the type argument could override categorical predictors. Right now plot always attempts boxplots when the x variable is a factor. It seems that the plot.factor method always gets called then. It would be nice if type could override that feature and I didn't have to make the x-axis numerical, suppress it, and then add it later. I'm not interested in a wrapper function since I've pretty much just described how to do that. I'm just wondering if there's a plot argument I've missed that can solve this.

For example, typically a boxplot is attempted in this case...

y <- 1:4
x <- factor(letters[1:4])
plot(y ~ x)

I'd prefer it to just plot the points and label the x-axes correctly. The following works but I was hoping for a simpler version.

nx <- length(x)
plot(y ~ 1:nx, xaxt = 'n')
axis(1, 1:nx, x, xlab = '')

I was hoping something like the following might work...

plot(y ~ x, type = 'n')
points(1:nx, y)

but no go. And type = 'p' doesn't do it either.

I believe this last failure is yet another example of inconsistency in R. Setting type = 'n' should be working in method calls as well or it should be mandatory that all plot functions use it (inherited or at least passed through ...). It's in plot.default.

like image 481
John Avatar asked Jan 29 '26 23:01

John


1 Answers

You could just call plot.default:

y<-rnorm(100)
x<-factor(sample(c("a","b","c"),size=100,replace=TRUE))
plot.default(x,y)

edit: Changed factor levels to characters so it is clear that this works even then.

like image 125
Jouni Helske Avatar answered Feb 01 '26 14:02

Jouni Helske



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!