Stacked Bar Graph reproduction in R

霸气de小男生 提交于 2019-12-02 09:18:48

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.

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!