在 ggplot2 中重新排序 x 类别仅适用于降序

问题描述 投票:0回答:1

我正在制作一个条形图,其中一个字符变量为 x,一个数值变量为 y,一个字符变量为填充。我想通过 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 个警告(In mean.default(X[[i]], ...):参数不是数字或逻辑:返回 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 个警告(在 mean.default(X[[i]], ...) 中:参数不是数字或逻辑:返回 NA)并生成下图。

r ggplot2 categories
1个回答
1
投票

认为这应该有效!

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))

© www.soinside.com 2019 - 2024. All rights reserved.