随时间在y轴上绘制多个变量

时间:2017-10-05 13:48:02

标签: r plot ggplot2

我有02.01.2007-30.12.2016时间范围内的以下数据集,其中包含两个费率以及这些确切费率的差异:

head(risk_free_rate_comparison)

   Dates `       Swap rate` `Sovereign bond yield rate` `Swap rate - Sovereign bond yield rate`
  <dttm>         <dbl>       <dbl>                       <dbl>
1 2007-01-02     408.9       380.9568                    27.9432
2 2007-01-03     410.3       380.4535                    29.8465
3 2007-01-04     409.2       381.3993                    27.8007
4 2007-01-05     414.3       385.0663                    29.2337
5 2007-01-08     413.1       384.2545                    28.8455
6 2007-01-09     415.5       384.9770                    30.5230

我想在x轴上绘制日期,以便在x轴上显示每年的结尾:2007-2016。

并且在y轴上具有以基点表示的其他三个变量,其中的线穿过数据点。拥有不同的线条样式会很不错,例如一个实线,一个虚线和一个虚线。 最后我想在图表的侧面有一个图例,显示变量名称。

或多或少像这个例子中没有网格:

plot example

1 个答案:

答案 0 :(得分:1)

对于简单快速的图表,请使用ggplot2

library(ggplot2)
library(reshape2)
d <- melt(risk_free_rate_comparison, "Dates")
d$Dates <- as.Date(d$Dates)
ggplot(d, aes(Dates, value, color = variable, linetype = variable)) +
    geom_line() +
    labs(color = NULL, linetype = NULL) +
    theme_classic() +
    theme(legend.position = "bottom")

reshape2::melt转换(对数据进行分组)。在这种情况下,您希望将Date放在x轴上。 theme_classic()是没有网格的ggplot2主题。

enter image description here