R中堆叠条形图的强制顺序

Forcing order of stacked bar chart in R

我的堆积条形图有问题。堆叠的顺序不同,而是按降序堆叠。我要修复堆叠

library(ggplot2)
library(reshape2)


df <- read.table(textConnection("title   '2016 phased' '2017 phased' '2018 phased' '2019 fully loaded'
                            'Pillar 1 minimum requirement (p1min)'    4,50%   4,50%   4,50%   4,50%
                            'Pillar 2 requirement (P2R)'  4,63%   1,75%   1,75%   1,75%
                            'Conservation Buffer' 0,63%   1,25%   1,88%   2,50%
                            'O-SII buffer'    0,50%   1,00%   1,50%   1,50%
                            'Countercyclical Buffer'  0,00%   0,15%   0,25%   0,35%"), header=TRUE)




df<-melt(df, id.vars="title", variable.name = "year")

df$value <- gsub(",", ".", df$value)

ggplot(df, aes(x = year, y = value, fill = factor(title,levels=c("Countercyclical Buffer","O-SII buffer","Conservation Buffer","Pillar 2 requirement (P2R)","Pillar 1 minimum requirement (p1min)")), arrange(desc(Level)), label = value)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank(),
    panel.grid.major = element_blank()
  ) +
  scale_fill_brewer()

此外,我无法摆脱显示为图例标题的因素(标题、级别...)。

你的值列是一个字符向量,但我很确定你希望它是数字。 df$value <- gsub(",", ".", df$value) 行正确地将逗号更改为小数点,但您仍然需要去掉百分号并将其转换为数字。

试试这个:

df$value <- gsub(",", ".", df$value)
df$value <- gsub("%", "", df$value)
df$value <- as.numeric(df$value)

这样做之后,我得到了一个看起来像我想象的那样的情节,正确堆叠。