r - 更改绘制线的顺序,以便在 ggplot 中的时间序列中位于顶部
问题描述
所以我正在为我正在从事的项目在 ggplot 上绘制一些时间序列数据。数据如下所示: 示例数据:
structure(list(Date = c("2015-01-01", "2015-02-01", "2015-03-01",
"2015-04-01"), Actual = c(500L, 600L, 700L, 750L), Fcst1 = c(600L,
610L, 634L, 650L), Fcst2 = c(500L, 630L, 875L, 900L), Fcst3 = c(500L,
600L, 754L, 800L), Fcst4 = c(500L, 600L, 700L, 760L)), class = "data.frame", row.names = c(NA,
-4L))
Date Actual Fcst1 Fcst2 Fcst3 Fcst4
2015-01-01 500 600 500 500 500
2015-02-01 600 610 630 600 600
2015-03-01 700 634 875 754 700
2015-04-01 750 650 900 800 760
.......... ... ... ... ... ...
数据本身又持续了 60 个月,总共有 40 个预测,每月调整一次。当我尝试绘制它时,我希望实际线位于顶部,但它最终被首先绘制。这是我正在使用的代码:
df <- df %>%
mutate(Date = ymd(Date))
colnames(df)[3:length(df)] <-
paste("df", colnames(df[, c(3:length(df))]), sep = "")
ggplot(
tidyr::pivot_longer(df, c(Fcst1:Fcst6, Actual), names_to = "Forecast", names_prefix = "df"),
aes(Date, value, color = Forecast)
) +
geom_line(size = 1) +
scale_color_manual(values = c(
"Fcst1" = "red", "Fcst2" = "blue",
"Fcst3" = "green", "Fcst4" = "yellow", "Fcst5" = "purple",
"Fcst6" = "orange", "Actual" = "black"
)) +
ggtitle(label = "Actuals vs Forecasts", subtitle = "Dataset") +
ylab("Rate") +
scale_y_continuous(labels = scales::comma)
我想保留图例中的顺序,所以我希望 Actuals 在顶部,然后是scale_color_manual
. 现在,实际值首先被绘制(这意味着它在所有其他预测之下),我希望它在顶部(最好用更粗的线,也许size=1.2
。谢谢!
解决方案
这是使用您包含的数据的可能解决方案。您必须对图例的级别进行格式化Forecast
和修改scale_color_manual()
。我为此添加了一个技巧:
library(tidyverse)
#Data
df <- structure(list(Date = c("2015-01-01", "2015-02-01", "2015-03-01",
"2015-04-01"), Actual = c(500L, 600L, 700L, 750L), Fcst1 = c(600L,
610L, 634L, 650L), Fcst2 = c(500L, 630L, 875L, 900L), Fcst3 = c(500L,
600L, 754L, 800L), Fcst4 = c(500L, 600L, 700L, 760L)), class = "data.frame", row.names = c(NA,
-4L))
#Format date
df <- df %>% mutate(Date = ymd(Date))
#Create data for plot
df2 <- tidyr::pivot_longer(df, c(Fcst1:Fcst4, Actual), names_to = "Forecast", names_prefix = "df")
#Format levels
labs <- unique(df2$Forecast)
i1 <- labs[which(labs=='Actual')]
i2 <- rev(labs[which(labs!='Actual')])
i3 <- c(i2,i1)
df2$Forecast <- factor(df2$Forecast,levels=i3,ordered = T)
#Plot
ggplot(df2,aes(Date, value, color = Forecast)) +
geom_line(size = 1) +
scale_color_manual(values = c(
"Fcst1" = "red", "Fcst2" = "blue",
"Fcst3" = "green", "Fcst4" = "yellow", "Fcst5" = "purple",
"Fcst6" = "orange", "Actual" = "black"
),guide = guide_legend(reverse=TRUE)) +
ggtitle(label = "Actuals vs Forecasts", subtitle = "Dataset") +
ylab("Rate") +
scale_y_continuous(labels = scales::comma)
输出:
推荐阅读
- c# - 如何在 Xamarin Forms 中创建带有上下移动动画的弹出视图
- node.js - 在 node_modules 中找不到模块
- c# - List 的动态数据类型导致应用程序崩溃
- python - os.rename() 用于文件扩展名 winerror2
- java - ScrollView+HorizontalScrollView+Scale 不能正确滚动
- excel - 如何根据存在的数据使用嵌套的 COUNT 公式进行不同的求和?
- c# - ElasticSearch - Nest - 映射嵌套在列表和字典中的命中
- angular - 如何使用 Bootstrap4 在 Angular8 中交换切换和标签的位置
- r - 我将如何创建组成数据的对数正态玩具数据集(观察结果是常数和的比例)?
- scala - 如何将 current_time - x(仅限小时)作为现有 Spark 数据框的列