-3

enter image description here I want legend to be sorted according to

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

Below is my ggplot code

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

In data frame plot.Data.Frame, models are stored in the sorted order.

R com
  • 13
  • 1
  • 5

1 Answers1

2

Order the factor levels with

plot.Data.Frame$VehicleDescription <- factor(
  plot.Data.Frame$VehicleDescription, 
  levels = paste0("model", 1:19))
)

before calling ggplot().