R - order of legend ggplot

2019-08-18 07:18发布

问题:

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: