ggplot stackbarplot legends sorting

时间:2018-05-15 04:40:57

标签: r sorting ggplot2 legend

enter image description here 我希望传奇按照

排序
model1
model2
model3
model4
model5
model6
model7
model8
model9
model10
model11
model12
model13
model14
model15
model16

以下是我的ggplot代码

p <- ggplot() +
  geom_bar(aes(y = n, x = Quarters, fill = VehicleDescription, 
               order = as.numeric(VehicleDescription)), 
           data = plot.Data.Frame, stat = "identity") + 
  #fill_palette=factor(VehicleDescription)) +
  theme(text = element_text(size = 12, colour = "blue"),
        axis.text.x = element_text(color = "black", size = 12, angle = 90, hjust=1),
        plot.title = element_text(hjust = 0.5)) +
  labs(title = plotTitle, x = xlab, y = ylab, subtitle = plotSubTitle) +
  scale_fill_manual(values=c("#990099", "#7DE367", "#799572", "#ddffcc", "#ffff99", 
                             "#669999", "#ffcc33", "#0000cc", "#ff8080", "#808080", 
                             "#00ffff", "#a31aff", "#800000", "#ff8000", "#ff0066", 
                             "#00bfff", "#004d00", "#660033")) 

p

在数据框plot.Data.Frame中,模型按排序顺序存储。

1 个答案:

答案 0 :(得分:2)

使用

订购因子水平
plot.Data.Frame$VehicleDescription <- factor(
  plot.Data.Frame$VehicleDescription, 
  levels = paste0("model", 1:19))
)

在致电ggplot()之前。