本文介绍了R - 传说ggplot的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有以下数据框: 作者< -c(University,Office,School ,大学,办公室,学校,大学,办公室,学校) Typ< -c(Text,Text,Text,Data 数据,数据,列表,列表,列表)数字 df 如果我申请: ggplot(df,aes(x = Author,y = Number,fill = Typ))+ geom_bar(stat ='identity')+ coord_flip() 然后我得到一个堆积条形图,其中条形图是按照日期框的顺序排列的,即 Text , Data , List ,但图例采用字母顺序排列。是否有任何(非蛮力,即手动)选项,以便我可以按照df的给定顺序重新排列图例,即在 Text , Data , List ? 有一堆数据框,就像矢量Typ(在每个数据框中也不同)中有更多的数据框那样,它们的顺序不应该改变,也显示在图例中。例程,绘制所有这些数据帧,所以我不能手动改变传说 - 我真的寻找一个例程友好的解决方案) 您可以根据它们在您的 data.frame 中的显示顺序自动设置您的级别: df $ Typ ggplot(df,aes(x = Author,y = Number,fill = Typ)) + geom_bar(stat ='identity')+ coord_flip() 您可以根据 df $ Typ 中的顺序更改因子的顺序: I have the following data frame:Author<-c("University","Office", "School","University","Office", "School","University","Office", "School")Typ<-c("Text", "Text", "Text","Data", "Data","Data", "List", "List", "List")Number<-c("3","1","6","4","4","2","8","1","1")df<-data.frame(Typ,Author,Number)If I apply:ggplot(df, aes(x=Author, y=Number, fill=Typ)) + geom_bar(stat='identity') + coord_flip()then I get a stacked bar plot where the bars are orders in the order of the date frame, i.e. Text, Data, List, but the legend is in alphabethic order. Is there any (non brute force, ie. by hand) option such that I can rearrange the legend also in the "given" order of the df, i.e. in Text, Data, List?(just to clarify - I have a bunch of data frames like that which are also bigger in the sense that the vectors "Typ" (which are also different in each data frame) have more entries whose order should not be changed and also displayed in the legend. I wrote a routine which plots all these data frames so I cannot change the legends manually - I am really looking for a routine friendly solution) 解决方案 You could automatically set your levels according to the order how they appear in your data.frame:df$Typ <- factor(df$Typ, levels = unique(df$Typ))ggplot(df, aes(x=Author, y=Number, fill=Typ)) + geom_bar(stat='identity') + coord_flip()In this way you change the order of your factor according to the order in df$Typ: 这篇关于R - 传说ggplot的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 20:35