【发布时间】:2019-05-17 13:38:55
【问题描述】:
我正在尝试将图例添加到时间序列图表中,但到目前为止我无法获得任何牵引力。我在下面提供了工作代码,它将三个经济数据系列拉到一个图表中,并应用了一些更改来获得我想要的格式/整体美感。我还应该补充一点,该图表正在绘制季度数据集的 y/y 变化。
我只能找到使用 scale_colour_manual 添加图例的个人示例 - 我在下面提供了代码。
理想情况下,图例只需要出现在带有颜色和折线图的图表的右侧。
任何帮助将不胜感激!
library(quantmod)
library(TTR)
library(ggthemes)
library(tidyverse)
Nondurable <- getSymbols("PCND", src = "FRED", auto.assign = F)
Nondurable$chng <- ROC(Nondurable$PCND,4)
Durable <- getSymbols("PCDG", src = "FRED", auto.assign = F)
Durable$chng <- ROC(Durable$PCDG,4)
Services <- getSymbols("PCESV", src = "FRED", auto.assign = F)
Services$chng <- ROC(Services$PCESV, 4)
ggplot() +
geom_line(data = Nondurable, aes(x = Index, y = chng), color = "#5b9bd5", size = 1, linetype = "solid") +
geom_line(data = Durable, aes(x = Index, y = chng), color = "#00b050", size = 1, linetype = "longdash") +
geom_line(data = Services, aes(x = Index, y = chng), color = "#ed7d31", size = 1, linetype = "twodash") +
theme_tufte() +
scale_y_continuous(labels = percent, limits = c(-0.01,.09)) +
xlim(as.Date(c('1/1/2010', '6/30/2019'), format="%d/%m/%Y")) +
labs(y = "Percent Change", x = "", caption = "Seasonally Adjusted Annual Rate. Retrieved from FRED & U.S. Bureau of Economic Analysis") +
ggtitle("Year-over-Year Spending Trend Changes of the US Consumer") +
scale_colour_manual(name = 'Legend',
guide = 'legend',
values = c('Nondurable' = '#5b9bd5',
'Durable' = '#00b050',
'Services' = '#ed7d31'),
labels = c('Nondurable',
'Durable',
'Services'))
我在运行程序时收到以下警告消息(但图表仍在绘制)。
Warning messages:
1: Removed 252 rows containing missing values (geom_path).
2: Removed 252 rows containing missing values (geom_path).
3: Removed 252 rows containing missing values (geom_path).
【问题讨论】:
-
对我来说,它会抛出 check_breaks_labels(breaks, labels) 中的错误:找不到对象“百分比”
-
奇怪 - 我已经编辑了我的代码以包含现在加载的所有包。
-
谢谢,我已经加载了
quantmod、ggplot2和ggthemes。缺少的是scales。 -
您是否在代码中看到任何会导致 scale_color_manual 不投射图例的错误?
-
不,我尝试了几种方法,但都没有奏效。明天我会回到这个。
标签: r ggplot2 quantmod geom-text economics