【问题标题】:Continuous to discrete legend on ggplot2 Rggplot2 R上的连续到离散图例
【发布时间】:2017-11-16 20:35:29
【问题描述】:


我正在尝试用 ggplot2 绘制曲线并按期限对它们进行分组。在我的数据集中,成熟度以剩余时间(以年为单位)表示。
我的问题是,在我的整个数据集中,我只有两个期限(0.15 和 0.2),但图例显示颜色为 0.15、0.16、0.17...
这是截图:

这是我的代码:

    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))

我尝试了 scale_color_discrete,但没有成功。谢谢!

【问题讨论】:

    标签: r plot ggplot2 legend


    【解决方案1】:

    在 aes 内,将 time_to_expiry 转换为因子 as.factor(time_to_expiry)

    + scale_color_manual(values = c(0.15, 0.2))
    

    【讨论】:

    • 它工作正常,但现在既没有任何颜色也没有任何线条
    • @AlexM 来自 tidyverse 页面:ggplot2.tidyverse.org/reference/scale_manual.html 看起来你可以做类似values = c(0.15 = 'red', 0.2 = 'blue' 的事情
    • @Highland 该解决方案的问题在于您修复了可能的到期日。如果数据集中出现一些额外的成熟度,则该解决方案将不再有效。我发表评论的解决方案效果很好,适用于所有数据集!非常感谢!
    【解决方案2】:

    解决方案:将time_to_expiry 替换为as.character(time_to_expiry) 按预期工作。 R 不能使用字符类型的变量生成连续值。
    非常感谢@Highland 几乎给出了解决方案!

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2021-12-04
      • 1970-01-01
      • 2023-03-06
      • 2015-11-09
      • 2018-06-20
      • 2014-11-14
      • 2018-03-21
      • 1970-01-01
      相关资源
      最近更新 更多