-1

I have the following data frame, nothing to fancy about it.

df_bar<-data.frame(capacity = c(no[2],no[1]-no[2],max(df_l$load)-no[1]), type = c("Nuclear","Coal","Gas"),a = c("Optimal","Optimal","Optimal"))

enter image description here

I tried to create a stacked barplot via ggplot, but I also need to make sure that I have a specific order in that plot, with N being the closest to the axis and C the furthest. However, the simple code leads to this.

ggplot(df_bar, aes(y=capacity, x=a, fill=type)) + 
geom_bar(position="stack", stat="identity")

enter image description here

How can I maybe alter the code so it respects the order I need?

vsh1996
  • 9
  • 2

1 Answers1

1

1.Create a minimal reproducible example.

df_bar<-data.frame(capacity = c(2,2,2),
                   type = c("Nuclear","Coal","Gas"),
                   a = c("Optimal","Optimal","Optimal"))

ggplot2 respects the order of ordered factors when plotting. We can use that to our advantage:

library(ggplot2)
ggplot(df_bar, aes(y=capacity, x=a, fill=factor(type, levels=c( "Coal", "Gas", "Nuclear")))) + 
  geom_bar(position="stack", stat="identity") +
  labs(fill="type")

enter image description here

dario
  • 6,415
  • 2
  • 12
  • 26