我需要帮助在条形图中绘制下面的数据框,我也会添加它。
Month Base Advanced
2008-01-01 20.676043 20.358472
2008-02-01 -57.908706 -62.368464
2008-03-01 -3.130082 -5.876791
2008-04-01 20.844747 14.162446
2008-05-01 39.882740 42.315828
2008-06-01 -12.802920 -13.333419
2008-07-01 -49.299693 -39.843041
2008-08-01 -4.563942 10.995445
2008-09-01 -100.018700 -77.054218
2008-10-01 -42.056913 -30.485998
我当前的代码效果不佳:
ggplot(ResidualsDataFrame,aes(x=Base,y=Advanced,fill=factor(Month)))+
geom_bar(stat="identity",position="dodge")+
scale_fill_discrete(name="Forecast",breaks=c(1, 2),
labels=c("Base", "Advanced"))+
xlab("Months")+ylab("Forecast Error")
这就是我想要做的。任何帮助表示感谢。
一个有用的技巧是将数据从“宽”更改为“长”。继续tidyverse
(因为您正在使用ggplot2
):
library(dplyr)
library(tidyr)
library(ggplot2)
x %>%
gather(ty, val, -Month)
# Month ty val
# 1 2008-01-01 Base 20.676043
# 2 2008-02-01 Base -57.908706
# 3 2008-03-01 Base -3.130082
# 4 2008-04-01 Base 20.844747
# 5 2008-05-01 Base 39.882740
# 6 2008-06-01 Base -12.802920
# 7 2008-07-01 Base -49.299693
# 8 2008-08-01 Base -4.563942
# 9 2008-09-01 Base -100.018700
# 10 2008-10-01 Base -42.056913
# 11 2008-01-01 Advanced 20.358472
# 12 2008-02-01 Advanced -62.368464
# 13 2008-03-01 Advanced -5.876791
# 14 2008-04-01 Advanced 14.162446
# 15 2008-05-01 Advanced 42.315828
# 16 2008-06-01 Advanced -13.333419
# 17 2008-07-01 Advanced -39.843041
# 18 2008-08-01 Advanced 10.995445
# 19 2008-09-01 Advanced -77.054218
# 20 2008-10-01 Advanced -30.485998
所以绘制它有点简单:
x %>%
gather(ty, val, -Month) %>%
ggplot(aes(x=Month, weight=val, fill=ty)) +
geom_bar(position = "dodge") +
theme(legend.position = "top", legend.title = element_blank())
使用的数据:
x <- read.table(text=' Month Base Advanced
2008-01-01 20.676043 20.358472
2008-02-01 -57.908706 -62.368464
2008-03-01 -3.130082 -5.876791
2008-04-01 20.844747 14.162446
2008-05-01 39.882740 42.315828
2008-06-01 -12.802920 -13.333419
2008-07-01 -49.299693 -39.843041
2008-08-01 -4.563942 10.995445
2008-09-01 -100.018700 -77.054218
2008-10-01 -42.056913 -30.485998', header=TRUE, stringsAsFactors=FALSE)
x$Month <- as.Date(x$Month, format='%Y-%m-%d')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句