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

时间:2018-02-22 15:58:49

标签: r ggplot2 stacked-chart

我的堆积条形图有问题。堆栈的顺序不同,但按递减顺序堆叠。我想修复堆叠

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

enter image description here

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

1 个答案:

答案 0 :(得分:1)

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

试试这个:

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

在这样做之后,我得到的情节看起来就像我想象的那样,经过恰当的堆叠。