R 按因子对分组堆叠条形图排序

R 按因子对分组堆叠条形图排序,r,ggplot2,charts,R,Ggplot2,Charts,我正在使用带有ggplot的R,我正在努力按照所需的顺序对分组条形图进行排序 目前使用的代码如下: levels(data.m$variable) <- c("% Worried about emigration", "% Worried both immigration and emigration", "% Worried about immigration", "% Neither / don't know") requi

我正在使用带有ggplot的R,我正在努力按照所需的顺序对分组条形图进行排序

目前使用的代码如下:

levels(data.m$variable) <- c("% Worried about emigration", "% Worried both immigration and emigration", 
                             "% Worried about immigration", "% Neither / don't know")

require(forcats)

ggplot(data.m, aes(fill = variable, Countries, value))+
  geom_bar(position = 'stack', stat = 'identity')+
  expand_limits(x=c(0,0))+
  coord_flip()
这就返回了这个图表:

然而,我想让这张图表的y轴按照更担心移民的国家进行排序


有人能帮我解决这个问题吗?

一个提示:小心levelsdata.m$变量y轴是按字母顺序绘制的。您需要将Countries变量定义为一个按所需顺序排列国家名称的因子。看看这个类似的问题/答案:太好了,它成功了!如果我还想以正确的顺序绘制“变量”的级别,该怎么办?1颜色红色2绿色等?在构建data.frame时,要保持颜色的顺序,请使用variable=factorvariable,levels={order\u of_colors},如上面的代码所示。这样可以保持因子的顺序,而不更改其值。
library(ggplot2)
library(dplyr)
#Dummy data
data.m = data.frame(Countries = c(rep("A",4),rep("B",4),rep("C",4)),
                    value = c(c(1,2,3,4),c(4,3,2,1),c(2,3,1,4))/10,
                    variable = factor(
                                  rep(c("% Worried about emigration", "% Worried both immigration and emigration", 
                                     "% Worried about immigration", "% Neither / don't know"),
                                   3), levels = c("% Worried about emigration", "% Worried both immigration and emigration", 
                                                  "% Worried about immigration", "% Neither / don't know"))
                    )

yticks = data.m %>% filter(variable=="% Worried about emigration") %>% arrange(value) %>% pull(Countries) %>% as.character()

## If you want it in descendant order use 'arrange(desc(value))'


ggplot(data.m,aes(fill = variable,Countries,value))+
  geom_bar(position = 'stack', stat = 'identity')+
  coord_flip()+
  scale_x_discrete(limits = yticks)