R语言 在ggplot2中重新排序x个类别仅适用于降序

xmjla07d  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(121)

我正在制作一个条形图,其中一个字符变量为x,一个数字变量为y,一个字符变量为fill。我想按fill变量对x个类别进行排序,但它只适用于降序排序。
我广泛地搜索了一下,到处都发现reorder(x,z)应该按照z的升序对x个类别进行排序,而reorder(x,-z)或reorder(x,desc(z))应该按照z的降序对x个类别进行排序。在我的例子中,当使用desc(z)时,我只得到了按z排序的类别;reorder(x,-z)返回一个错误(!一元运算符的参数无效),而使用z只是按x对它们进行排序。
这段代码几乎给出了我想要的:

df<- data.frame(x=c("loc9","loc2", "loc3","loc7","loc5","loc6","loc4","loc1","loc8"), y=c(1,2,5,3,5,6,7,9,5), z=c("A","A", "B","B","B","B","C","C","C"), se=c(0.1, 0.14, 0.2, 1,0.25,0.3,0.21,0.23,0.2), n=c(2,2,3,2,1,1,3,5,4))
plot<- df %>%
  ggplot(aes(x=reorder(x, desc(z)), y=y, fill=z))+
  geom_bar(stat="identity")+
  geom_errorbar(aes(reorder(x, desc(z)), ymin=y-se, ymax=y+se), width=0.3, colour="blue3", alpha =0.9, size=0.7)+
  geom_text(aes(x=reorder(x, desc(z)), y=0.5, label=n))+
  theme(legend.position="bottom",plot.title = element_text(size=12),
        text = element_text(size=14),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
  ggtitle("Here the title of the plot") +
  labs(x="", ylab="Lab of y", fill=NULL)

下面的代码给出了36个警告(在mean.default(Xi,...)中):参数不是数字或逻辑:返回NA)并生成下图。

plot<- df %>%
  ggplot(aes(x=reorder(x, desc(z)), y=y, fill=z))+
  geom_bar(stat="identity")+
  geom_errorbar(aes(reorder(x, desc(z)), ymin=y-se, ymax=y+se), width=0.3, colour="blue3", alpha =0.9, size=0.7)+
  geom_text(aes(x=reorder(x, desc(z)), y=0.5, label=n))+
  theme(legend.position="bottom",plot.title = element_text(size=12),
        text = element_text(size=14),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
  ggtitle("Here the title of the plot") +
  labs(x="", ylab="Lab of y", fill=NULL)
plot

这段代码给出了36个警告(平均值为.default(Xi,...)):参数不是数字或逻辑:返回NA)并生成下图。

y1aodyip

y1aodyip1#

我想这个应该能用!

df$z <- factor(df$z, levels=c("A", "B"  , "C"))

df = df[order(df$z, df$x), ]

df$x = factor(df$x, levels = unique(df$x))

plot<- df %>%
  ggplot(aes(x=x, y=y, fill=z))+
  geom_bar(stat="identity")+ geom_errorbar(aes(x, ymin=y-se, ymax=y+se), width=0.3, colour="blue3", alpha =0.9, size=0.7)+ geom_text(aes(x=x, y=0.5, label=n))

plot

更新:或使用fct_reorder(forcats)按字母顺序排序

plot<- df %>% ggplot(aes(fct_reorder(x,z), y=y, fill=z)) + geom_bar(stat="identity")+ geom_errorbar(aes(x, ymin=y-se, ymax=y+se), width=0.3, colour="blue3", alpha =0.9, size=0.7)+ geom_text(aes(x=x, y=0.5, label=n))

相关问题