简体   繁体   English

R - geom_bar分组条形图,带有分组标签

[英]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: 第二个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. 即使我有从10月到3月的月份,R标志着9月而不是12月。 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. zoo::as.yearmon期望%b即系统语言环境中的缩写月份名称(例如Jan,Feb等)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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