0

I have a dataframe named molten as follows:

Name value  Dummy     Variable
A    40     Values    A_Values
B    20     Values    B_Values
C    100    Values    C_Values
D    80     Values    D_Values
A    30     Dummies   A_Dummies
B    40     Dummies   B_Dummies
C    0      Dummies   C_Dummies
D    10     Dummies   D_Dummies

I am using the following code to plot a chart:

ggplot(data=molten,aes(y=value,x=Names))+
  geom_bar(aes(fill=Variable), stat = "identity")+

The resultant graph plotted is as follows:

enter image description here

I want the graph to look like as follows:

enter image description here

Basically, what is happening is the '_Values' are getting printed first and then above that '_Dummies' are getting plotted. I want the reverse of that to happen. I want the '_Dummies' values to be plotted first and then the '_Values'. Is there anyway i can do that?

What I have observed that is if I replace 'Dummies' and '_Dummies' in the DF with any string which comes alphabetically after 'Values', the graph gets plotted the way I want it (like I have showed above when I used '_Values1'). However, I do not want to change the names of the strings in the DF.

I want to plot the 2nd graph without having to change the dataframe values. Is there anyway I can change the order in which ggplot plots the graph?

Aneesh
  • 63
  • 2
  • 12
  • 4
    I assume the order is defined by the order of the factor levels. Set your variables as factor with your desired order. This should solve the issue. – Andre Elrico Mar 27 '18 at 07:36
  • Andre is correct, ordering issues in ggplot are basically always solved by reordering your factor. Alternatively, you can change the limits of the color scale. See the duplicate and the links therein for some ways how to do these different things. – Axeman Mar 27 '18 at 07:40
  • Thanks. This solved the issue. But I have to change the order again if my names change. Is there any way the order of the Variable will change dynamically as I change the names? – Aneesh Mar 27 '18 at 07:55
  • Use something like `df$Variable <- factor(df$Variable, unique(df$Variable))` to always get them in the order of appearance in the data (instead of alphabetical). – Axeman Mar 27 '18 at 08:45

0 Answers0