ggplot2 每个方面的不同因子顺序

2024-05-01

我正在尝试创建一个克利夫兰点图,在本例中为 J 和 K 给出两个类别。问题是元素 A、B、C 都在这两个类别中,所以 R 一直放屁。我做了一个简单的例子:

x <- c(LETTERS[1:10],LETTERS[1:3],LETTERS[11:17])
type <- c(rep("J",10),rep("K",10))
y <- rnorm(n=20,10,2)
data <- data.frame(x,y,type)
data
data$type <- as.factor(data$type)
nameorder <- data$x[order(data$type,data$y)]
data$x <- factor(data$x,levels=nameorder)

ggplot(data, aes(x=y, y=x)) +
geom_segment(aes(yend=x), xend=0, colour="grey50") +
geom_point(size=3, aes(colour=type)) +
scale_colour_brewer(palette="Set1", limits=c("J","K"), guide=FALSE) +
theme_bw() +
theme(panel.grid.major.y = element_blank()) +
facet_grid(type ~ ., scales="free_y", space="free_y") 

理想情况下,我想要两个类别(J,K)单独的点图,每个因子(向量x)相对于y向量递减。最终发生的情况是,这两个类别都不是从最大到最小,而是最终不稳定。请帮忙!


不幸的是,因素只能有一组水平。我发现做到这一点的唯一方法实际上是根据您的数据创建两个单独的 data.frames 并重新调整每个中的因子。例如

data <- data.frame(
    x = c(LETTERS[1:10],LETTERS[1:3],LETTERS[11:17]),
    y = rnorm(n=20,10,2),
    type= c(rep("J",10),rep("K",10))
)
data$type <- as.factor(data$type)

J<-subset(data, type=="J")
J$x <- reorder(J$x, J$y, max)
K<-subset(data, type=="K")
K$x <- reorder(K$x, K$y, max)

现在我们可以用以下方法绘制它们

ggplot(mapping = aes(x=y, y=x, xend=0, yend=x)) + 
   geom_segment(data=J, colour="grey50") +
   geom_point(data=J, size=3, aes(colour=type)) +
   geom_segment(data=K, colour="grey50") +
   geom_point(data=K, size=3, aes(colour=type)) + 
   theme_bw() +
   theme(panel.grid.major.y = element_blank()) +
   facet_grid(type ~ ., scales="free_y", space="free_y") 

这导致

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ggplot2 每个方面的不同因子顺序 的相关文章

随机推荐