Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

r - Tricks to override plot.factor?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...