简体   繁体   English

堆叠条形图 R 中的顺序

[英]Order in stacked barplot R

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

在此处输入图片说明

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.我试图通过 ggplot 创建一个堆叠的条形图,但我还需要确保我在该图中有一个特定的顺序,N 离轴最近,C 最远。 However, the simple code leads to this.然而,简单的代码导致了这一点。

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

在此处输入图片说明

How can I maybe alter the code so it respects the order I need?我怎样才能改变代码以使其符合我需要的顺序?

1.Create a minimal reproducible example . 1.创建一个最小的可重现示例

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. ggplot2在绘图时尊重有序因子的顺序。 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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM