简体   繁体   中英

R - geom_bar Grouped Barchart with grouped Labels

I am combining a stacked bar chart and a line graph.

Here is the reproducible code for the dataframes:

df1 <- data.frame(month = c("Okt 2017", "Okt 2017", "Okt 2017", "Nov 2017", "Nov 2017", "Nov 2017", "Dez 2017", 
                            "Dez 2017", "Dez 2017", "Jan 2018", "Jan 2018", "Jan 2018", "Feb 2018", "Feb 2018", "Feb 2018",
                             "Mrz 2018", "Mrz 2018", "Mrz 2018"), 
                 source = c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c"),
                 value1 = c(sample (c(1000L:4000L),18, replace = FALSE))
                 )

df1$month <- as.yearmon(df1$month)
df1 <- arrange(df1, month)

Second df:

df2 <- data.frame(month = c("Okt 2017", "Nov 2017", "Dez 2017", "Jan 2018", "Feb 2018", "Mrz 2018"), 
                  value2 = c(sample (c(5000000L:6000000L),6, replace = FALSE))
                  )

df2$month <- as.yearmon(df2$month)
df2 <- arrange(df2, month)

and the code for the plotting:

ggplot() +   
geom_bar(data = df1, aes(month, value1*5000000/5000, fill = source), stat="identity", position = "stack") +
geom_point(data = df2, aes(month, value2), color = "blue")+   
geom_line(data = df2, aes(month, value2), group = 1, color = "blue") +  
labs(x = "month", y="value2 (line)") +   scale_y_continuous(sec.axis = sec_axis(~.*5000/5000000, name = "value1 (bars)"), 
                     labels= format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +   
scale_x_yearmon(format = "%Y-%b", n = 6) +  
scale_fill_manual(values= c("darkseagreen4","darkseagreen", "darkseagreen3", "darkseagreen2")) + 
theme_light()

Even though I have the months from October to March, R labels a September and no December. Does anybody know what I am doing wrong here?

zoo::as.yearmon expects %b ie the abbreviated month name (eg Jan, Feb etc) in the locale of your system.

In this case you seem to be using month in German format but you locale is different. You can check your current setting using

Sys.getlocale()


So one of the approach could be to set your locale accordingly (or you may use data having month name in "English" format) before running your code

Sys.setlocale("LC_TIME", "de_DE")  #Mac
Sys.setlocale("LC_TIME", "German") #Windows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM