如何纠正条形图的顺序?

时间:2018-10-18 13:37:00

标签: ggplot2 plot

我想绘制两个误差度量(MAE,RMSE)的月度百分比变化,但是这些图的顺序不正确。它们应从上到下水平移动,如H1,H2,H3等,并在右下角以H12结尾。取而代之的是,它们越过顶部进入H1,H10,H11,H12(我假设是因为H之后的第一个数字是1)。有人可以告诉我如何解决此问题吗?

代码是...

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)

和情节看起来像... enter image description here

2 个答案:

答案 0 :(得分:1)

您可以在每个1-9前面加一个0。

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)

这导致以下图像 enter image description here

答案 1 :(得分:0)

通过在数据框中添加一个计数字段来解决这个问题。

新代码是:

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"))

产生...

enter image description here