[R] Help with staked bar plot values

Bill Poling B|||@Po||ng @end|ng |rom ze||@@com
Wed May 29 17:49:33 CEST 2019


Hello

#RStudio Version 1.2.1335
sessionInfo()
# R version 3.6.0 Patched (2019-05-19 r76539)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 10 x64 (build 17134)


I am all over the google map with this so far but have made progress.

#https://www.r-graph-gallery.com/stacked-barplot/

#https://stackoverflow.com/questions/20349929/stacked-bar-plot-in-r

#https://stackoverflow.com/questions/41908635/r-ggplot2-adding-value-to-bar-plot

Here is my data for example use:

df6 <- df5[,c(1,2,3)]

head(df6,n=12)

Month_Yr       RPct     ASPct
1   2018-01 0.03060779 0.1288720
2   2018-02 0.02584442 0.1087038
3   2018-03 0.02879822 0.1268878
4   2018-04 0.02661778 0.1204089
5   2018-05 0.02390651 0.1158945
6   2018-06 0.02831802 0.1174230
7   2018-07 0.02545577 0.1106545
8   2018-08 0.02738861 0.1179146
9   2018-09 0.02826573 0.1286884
10  2018-10 0.02167206 0.1213102
11  2018-11 0.02203140 0.1158986
12  2018-12 0.02209121 0.1309418

These are percentages by Month_Yr

dput(df6)
structure(list(Month_Yr = c("2018-01", "2018-02", "2018-03",
"2018-04", "2018-05", "2018-06", "2018-07", "2018-08", "2018-09",
"2018-10", "2018-11", "2018-12"), RPct = c(0.0306077919610775,
0.0258444184406978, 0.0287982244057369, 0.0266177822179555, 0.0239065089349008,
0.0283180203081446, 0.0254557749242774, 0.0273886068149913, 0.028265726678494,
0.0216720600309651, 0.022031396916971, 0.0220912074431471), ASPct = c(0.128871966484723,
0.108703765196302, 0.126887785714588, 0.120408859429047, 0.11589445999452,
0.11742296270427, 0.110654529518569, 0.117914621843884, 0.128688428092512,
0.121310162536382, 0.115898591408793, 0.13094179316738)), class = "data.frame", row.names = c(NA,
-12L))

My basic stack bar plot works

tbl<-melt(df6,id.vars="Month_Yr")

ggplot(tbl,aes(x=Month_Yr,y=value,fill=variable))+geom_bar(stat='identity') +
  scale_y_continuous(labels = scales::percent)

So I would like a stacked Bar plot of same but adds the value, in percentage 25% 75% etc into the bar itself.

Here is my attempt so far

ggplot(tbl,aes(x=Month_Yr,y=value,fill=variable))+geom_bar(stat='identity') +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = sprintf("%.1f", value), y= value),  vjust = 3)+
  guides(fill=FALSE)

This version of plot has 0.1 in all the bars at ~ the top of the lower bar and 0.0 at the bottom of the lower bar?

1. How can I get the correct values into the top and bottom bars please?
2. Also how can I get the Y axis to have 10 breaks from 0 to 100 rather than the 0 to 15%

Thank you for your support

WHP









Confidentiality Notice This message is sent from Zelis. ...{{dropped:13}}



More information about the R-help mailing list