gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:33:04 27 4
gpt4 key购买 nike

在本例中,我正在尝试为两个类别创建一个克利夫兰点图 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")

结果是

enter image description here

关于r - ggplot2 每个方面的不同因子顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24255305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com