我在图表背景中添加衰退条时遇到了一些问题。这样做的正确方法是什么? 我试图为背景定义geom_rect(.....),但这没有成功。
以下是我获取数据的代码:
library(quantmod)
library(dplyr)
library(ggplot2)
getSymbols("USPRIV",src="FRED")
getSymbols("USGOVT",src="FRED")
#convert data from quantmod into dataframes
uspriv.df <- data.frame(date= index(USPRIV),USPRIV$USPRIV)
usgovt.df <- data.frame(date= index(USGOVT),USGOVT$USGOVT)
#calculate month-to-month difference
d.uspriv <- dplyr::mutate(uspriv.df[-1,], duspriv = uspriv.df$USPRIV[-1]-uspriv.df$USPRIV[-nrow(uspriv.df)])
d.usgovt <- dplyr::mutate(usgovt.df[-1,], dusgovt = usgovt.df$USGOVT[-1]-usgovt.df$USGOVT[-nrow(usgovt.df)])
df <- dplyr::left_join(d.uspriv, d.usgovt, by = "date")
#shorten dataframe, starting in 2007
df.2007 <- dplyr::filter(df, date >= "2007-01-01")
df1.2007 <- dplyr::select(df.2007, date, duspriv, dusgovt)
df1 <- melt(df1.2007, id="date")
ggplot(df1, aes(x=date, y=value)) +
geom_bar(aes(fill=variable),
stat="identity",
position=position_dodge()) +
scale_fill_brewer(palette="Dark2")
这会生成此图here:
包含经济衰退条的最有效方法是什么? 这是获取数据的代码
getSymbols("USREC",src="FRED")
usrec.df <- data.frame(date= index(USREC), USREC$USREC)
如果我将衰退数据包含在数据框中然后融化它,我将如何定义ggplot部分?
非常感谢。
答案 0 :(得分:1)
这是一个更强大的解决方案。当有多次经济衰退时,这不应该失败(具有讽刺意味的是......)。感谢用户bergant
。
注意:您仍需要确保在您考虑的时间范围内存在匹配的USREC数据。
我在 1965 开始做了一个例子。
library(quantmod)
library(dplyr)
library(reshape2)
library(ggplot2)
getSymbols("USPRIV",src="FRED")
getSymbols("USGOVT",src="FRED")
#convert data from quantmod into dataframes
uspriv.df = data.frame(date= index(USPRIV),USPRIV$USPRIV)
usgovt.df = data.frame(date= index(USGOVT),USGOVT$USGOVT)
#calculate month-to-month difference
d.uspriv = dplyr::mutate(uspriv.df[-1,], duspriv = uspriv.df$USPRIV[-1]-uspriv.df$USPRIV[-nrow(uspriv.df)])
d.usgovt = dplyr::mutate(usgovt.df[-1,], dusgovt = usgovt.df$USGOVT[-1]-usgovt.df$USGOVT[-nrow(usgovt.df)])
df = dplyr::left_join(d.uspriv, d.usgovt, by = "date")
#shorten dataframe, starting in 1965
df.1965 = dplyr::filter(df, date >= "1965-01-01")
df1.1965 = dplyr::select(df.1965, date, duspriv, dusgovt)
df1 = melt(df1.1965, id="date")
#########
getSymbols("USREC",src="FRED")
usrec = data.frame(date= index(USREC), USREC$USREC)
rownames(usrec) = NULL
new_df = merge(df1, usrec)
##############
# Thanks go out to @bergant for this bit:
dif = diff(new_df$USREC)
new_df$Status = factor(c(0, dif) - 2 * c(dif, 0), levels = -3:3)
levels(new_df$Status) = c(rep(0, 4), "Start", "End", "Start&End")
##############
start_end_dt = data.frame(
xmin = as.Date(new_df$date[new_df$Status == "Start"])
, xmax = as.Date(new_df$date[new_df$Status == "End"])
)
##############
其余的很容易:
ggplot(new_df, aes(x=date, y=value)) +
geom_rect( inherit.aes = FALSE
, data = start_end_dt
, aes(xmin = xmin
, xmax = xmax
, ymin=-Inf
, ymax=+Inf)
, fill='gray'
, alpha=0.5) +
geom_bar(aes(fill=variable),
stat="identity",
position=position_dodge()) +
scale_fill_brewer(palette="Dark2") +
theme_bw() +
theme( panel.grid.minor = element_blank(), panel.grid.major = element_blank() )