如何重新排列分组条形图中的组

Gon*_*alo 5 r bar-chart ggplot2

我想创建一个分组条形图,其中的组以特定顺序出现。这里有一个详细的例子。

df <- data.frame(Groups = c("B","B","B","C","C","A","A","A","A","A"), 
                 Ages = c(3,4,4,5,3,4,5,3,3,5))

df_cast <- dcast(data = df, formula = Groups ~ Ages)    
df_bars <- melt(data = df_cast, id.vars = 'Groups')

ggplot(data = df_bars, aes( x = Groups, y = value, fill = variable ) ) + 
    geom_bar( stat = 'identity', position = 'dodge' ) + 
    labs(title="Groups ages", x = "Groups", y = "Frecuency") + 
    labs(fill = "Ages") + theme(plot.title = element_text(hjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

组是 B、C 和 A,我希望它们按顺序出现在条形图中,上面的命令按字母顺序排列它们。

akr*_*run 10

我们需要在“群组”转换为factorlevels该订单中指定

df_bars$Groups <- factor(df_bars$Groups, levels = c('B', 'C', 'A'))
Run Code Online (Sandbox Code Playgroud)

然后使用ggplotOP帖子中的代码

在此处输入图片说明