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
634 views
in Technique[技术] by (71.8m points)

r - Is there an equivalent in ggplot to the varwidth option in plot?

I am creating boxplots using ggplot and would like to represent the sample size contributing to each box. In the base plot function there is the varwidth option. Does it have an equivalent in ggplot?

For example, in base plot

data <- data.frame(rbind(cbind(rnorm(700, 0,10), rep("1",700)),
                         cbind(rnorm(50, 0,10), rep("2",50))))
data[ ,1] <- as.numeric(as.character(data[,1]))
plot(data[,1] ~ as.factor(data[,2]), varwidth = TRUE)

enter image description here

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Not elegant but you can do that by:

data <- data.frame(rbind(cbind(rnorm(700, 0,10), rep("1",700)),
? ? ? ? ? ? ? ? ? ? ? ? ?cbind(rnorm(50, 0,10), rep("2",50))))
data[ ,1] <- as.numeric(as.character(data[,1]))
w <- sqrt(table(data$X2)/nrow(data))
ggplot(NULL, aes(factor(X2), X1)) + 
  geom_boxplot(width = w[1], data = subset(data, X2 == 1)) +
  geom_boxplot(width = w[2], data = subset(data, X2 == 2))

enter image description here

If you have several levels for X2, then you can do without hardcoding all levels:

ggplot(NULL, aes(factor(X2), X1)) + 
  llply(unique(data$X2), function(i) geom_boxplot(width = w[i], data = subset(data, X2 == i)))

Also you can post a feature request: https://github.com/hadley/ggplot2/issues


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

...