Angus
Angus

Reputation: 355

How do I correct the ordering of the barcharts?

I want to plot monthly percentage change of two error metrics (MAE, RMSE), but the ordering of the plots are not correct. They should go horizontally from top to bottom as H1, H2, H3, .. etc, and ending with H12 at the bottom right. In stead they go H1, H10, H11, H12 across the top (I assume because the first number after the H is a 1). Could someone show me how to fix this please?

The code is ...

library(ggplot2)
# dataset
metric=c(rep("MAE" , 12) , rep("RMSE" , 12) )
horizon=rep(c("H1" , "H2" , "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "H11", "H12") , 2)
Perc_Change=c(-24,-55,-40,0,0,-2,-22,-28,-12,-12,-2,-8,-15,-44,-37,0,0,3,-21,-28,-7,-15,3,-9)
data=data.frame(metric,horizon,Perc_Change)

# Faceting
ggplot(data, aes(y=Perc_Change, x=metric, color=metric, fill=metric)) + 
  geom_bar( stat="identity") +    
  facet_wrap(~horizon)

and the plot looks like ... enter image description here

Upvotes: 0

Views: 23

Answers (2)

Angus
Angus

Reputation: 355

Figured it out by adding a count field in the data frame.

New code is:

library(ggplot2)
# dataset
metric=c(rep("MAE" , 12) , rep("RMSE" , 12) )
horizon=rep(c("January 2017" , "February 2017" , "March 2017", "April 2017", "May 2017", "June 2017",
              "July 2017", "August 2017", "September 2017", "October 2017", "November 2017", "December 2017") , 2)
Perc_Change=c(-24,-55,-40,NA,NA,-2,-22,-28,-12,-12,-2,-8,-15,-44,-37,NA,NA,3,-21,-28,-7,-15,3,-9)
count=rep(c(1,2,3,4,5,6,7,8,9,10,11,12),2)
data=data.frame(count,metric,horizon,Perc_Change)

# Faceting
ggplot(data, aes(y=Perc_Change, x=metric, fill=metric)) + 
  geom_bar( stat="identity") +    
  facet_wrap(count~horizon)+scale_fill_manual(values=c("darkblue", "darkred"))

which produces ...

enter image description here

Upvotes: 0

Mr_Z
Mr_Z

Reputation: 539

You could prepend a 0 to each 1-9.

library(ggplot2)
# dataset
metric=c(rep('MAE' , 12) , rep('RMSE' , 12) )
horizon=c('H01' , 'H02' , 'H03', 'H04', 'H05', 'H06', 'H07', 'H08', 'H09', 'H10', 'H11', 'H12')
Perc_Change=c(-24,-55,-40,0,0,-2,-22,-28,-12,-12,-2,-8,-15,-44,-37,0,0,3,-21,-28,-7,-15,3,-9)
data=data.frame(metric,horizon,Perc_Change)

# Faceting
ggplot(data, aes(y=Perc_Change, x=metric, color=metric, fill=metric)) + 
  geom_bar( stat='identity') +    
  facet_wrap(~horizon)

This leads to following image enter image description here

Upvotes: 1

Related Questions