R - order of legend ggplot

廉价感情. 提交于 2019-12-12 03:01:24

问题


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)


回答1:


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:



来源:https://stackoverflow.com/questions/31807657/r-order-of-legend-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!