Stacked Bar Graph reproduction in R

后端 未结 2 1936
花落未央
花落未央 2021-01-28 12:01

I am trying to reproduce this graph in R without success:

But for more years

This is the data:

title   2016 phased 2017 phased 2018 pha         


        
相关标签:
2条回答
  • 2021-01-28 12:47

    Using the original data that you provided.

    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)
    

    melt data.

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

    Replace commas from values.

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

    And adapting the answer provided here: Showing data values on stacked bar chart in ggplot2

    ggplot(df, aes(x = year, y = value, fill = title, 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()
                      )
    

    Provides you with this.

    0 讨论(0)
  • 2021-01-28 12:50

    Read the data in the first instance including these arguments:

    read.xlsx(..., header = T, check.names = F)
    

    This will stop your headers being included in the long format data frame and also stop R appending the X's and .'s into your legend labels. Hopefully this will fix your y-axis tick marks by making all values numeric (it currently contains strings, making it character type).

    If this doesn't help, you could remove the titles from the dataframe into a legend_labs vector. You can the use this to add custom labels to the legend:

    legend_labs <- c("Pillar 1", "Pillar 2"...)
    ggplot(...)
    + scale_color_manual(labels = legend_labs)
    

    Then you could use this to label your x, y and legend titles:

    + labs(x = "X Title", y = "Y title", fill = "Legend Title")
    
    0 讨论(0)
提交回复
热议问题