ggplot
tidyr::gather
为了将数据转换成长格式,绘图就简化了,我们可以在不改变绘图代码的情况下拥有任意多个变量:
df_long = tidyr::gather(df, "var", "value", -date)
head(df_long)
# # A tibble: 6 x 3
# date var value
# <date> <chr> <dbl>
# 1 1967-07-01 psavert 12.5
# 2 1967-08-01 psavert 12.5
# 3 1967-09-01 psavert 11.7
# 4 1967-10-01 psavert 12.5
# 5 1967-11-01 psavert 12.5
# 6 1967-12-01 psavert 12.1
请注意,我们现在为
y
var
geom_area
图层。如果有两个以上的变量
变量
# plot
ggplot(df_long, aes(x = date)) +
geom_area(aes(y = value, fill = var)) +
labs(
title = "Area Chart of Returns Percentage",
subtitle = "From Wide Data format",
caption = "Source: Economics",
y = "Returns %"
) +
scale_x_date(labels = lbls, breaks = brks) + # change to monthly ticks and labels
scale_fill_manual(name="",
values = c("psavert"="#00ba38", "uempmed"="#f8766d")) + # line color
theme(panel.grid.minor = element_blank()) # turn off minor grid
作为旁注,我建议使用代码注释来(a)解释
为什么?
你做事,以及(b)记录你做事的任何不寻常或棘手的方式。我想你会发现更明显的评论
# title and caption
title = "Area Chart of Returns Percentage"