如何在分组条形图中对组进行重新排序

编程入门 行业动态 更新时间:2024-10-26 16:22:57
本文介绍了如何在分组条形图中对组进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

df < - data.frame(Groups = c(B,B,B C,C,A,A,A,A,A年龄= 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))

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

将Groups转换为 factor ,并按照该顺序指定 levels df_bars $组< - factor( df_bars $ Groups,levels = c('B','C','A'))

然后在OP的帖子中使用 ggplot 代码

I want to create a grouped bar-chart with groups appearing in a specific order. Here is a detailed example.

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

The groups are B, C and A, and I want them to appear in that order in the bar-chart, the above command arrange them in alphabetic order.

解决方案

We need to convert the 'Groups' to factor with levels specified in that order

df_bars$Groups <- factor(df_bars$Groups, levels = c('B', 'C', 'A'))

Then using the ggplot code in the OP's post

更多推荐

如何在分组条形图中对组进行重新排序

本文发布于:2023-10-24 08:27:08,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中对   如何在   条形图

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!