代码之家  ›  专栏  ›  技术社区  ›  Yrden

R中堆叠条形图的强制顺序[重复]

  •  0
  • Yrden  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  1
  •   camille    6 年前

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

    尝试以下操作:

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

    做了这些之后,我得到了一个情节,看起来就像我想象中的你在追求的一样,堆叠得很好。