我正在尝试向时间序列图添加图例,但到目前为止我一直无法获得任何关注。我提供了下面的工作代码,该代码将三个经济数据系列汇总到一张图表中,并应用了几处更改以形成我想要的格式/整体美感。我还应该补充一点,该图表绘制了季度数据集的y / y变化。
我只能使用scale_colour_manual来添加图例来查找个人的示例-我在下面提供了代码。
理想情况下,图例只需显示在带有颜色和折线图的图形的右侧。
任何帮助将不胜感激!
library(quantmod)
library(ggplot2)
library(xts)
library(scales)
library(ggthemes)
library(Quandl)
library(grid)
library(gridExtra)
library(dplyr)
library(lubridate)
library(TTR)
library(readxl)
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).
答案 0 :(得分:0)
收到此错误有两个原因:
xlim()
或scale_y_continuous(..., limits = ...)
时,ggplot会在绘制之前从数据中删除超出这些限制的值,并将该警告显示为FYI。注释掉这两行之后,您仍然会看到一条有关已删除值但数量少得多的消息。这是因为NA
列的前4行中有chng
个值。在所有三个数据集中都是如此。要显示刻度,您需要像在aes()
中那样在aes(..., color = "Nondurable")
中添加一些区别线。查看此解决方案是否适合您:
ggplot() +
geom_line(data = Nondurable, aes(x = Index, y = chng, color = "Nondurable"), size = 1, linetype = "solid") +
geom_line(data = Durable, aes(x = Index, y = chng, color = "Durable"), size = 1, linetype = "longdash") +
geom_line(data = Services, aes(x = Index, y = chng, color = "Services"), size = 1, linetype = "twodash") +
theme_tufte() +
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",
values = c("#5b9bd5","#00b050","#ed7d31"),
labels = c("Nondurable", "Durable", "Services"
)
)