在 r 中使用 ggplot 覆盖两个不同的数据集

时间:2021-06-23 12:55:14

标签: r ggplot2

我有一个手动模拟的 GARCH 项,我试图使用 ggplot 将其与原始数据集一起绘制。生成的图应该是这样的

enter image description here

使用 geom_line 和 sec_axis 组合数据集不起作用,因为它只返回红色项的缩放轴。

关于如何实现这个理想的情节有什么想法吗?谢谢

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。我将第二个(红线)数据集放大了一个因子(在本例中为 880000),并使用 trans 中的 sec.axis 函数将第二个轴缩小了相同的因子。代码如下:

geom_line(aes(y= SPX.Index, col= "SPX.Index"), size= 1.1)+ 
  geom_line(aes(y= Model*880000, col="local Vol Model"), size=1.1)+ 
  scale_y_continuous(sec.axis=sec_axis(name= "Local Vol Model", trans= ~./880000))+ 
  scale_color_manual(values = c("#990000", "#006633" ))+ 
  theme_minimal()+theme(legend.position='bottom')+ 
  theme(panel.grid.major.x = element_blank(),panel.grid.minor.x = element_blank())