Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder the groups in a grouped bar-chart [duplicate]

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.

like image 581
Gonzalo Avatar asked Nov 27 '17 06:11

Gonzalo


People also ask

How do you reorder bars in a bar graph?

Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.

How do you arrange a bar graph in ascending order in R?

To reorder the bar graph in descending or ascending order, use the function reorder( ). There is no need to rename the data frame.


1 Answers

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

enter image description here

like image 107
akrun Avatar answered Oct 09 '22 21:10

akrun