我正在用R进行编码,并且具有以下数据框和图:
df1 <- data.frame(term = c(1,2,3,4, 1,2,3,4, 2, 4),
vol=c(10, 11, 12, 12.3, 9, 9.5, 11, 15, 13, 20),
date=c("2019","2019","2019","2019","2018","2018","2018","2018", "2019swp","2019swp"), stringsAsFactors = F)
plot_ly(data = df1, x=~term, y=~vol) %>% add_trace(type='scatter',mode='lines', color=~date) %>%
layout(title=paste0("Impled Vol Term Structure"),
xaxis=list(title='Term (years)'),
yaxis=list(title='Implied Vol (%)'))
但是,我想实现的一种方法是告诉我的情节:“如果该线是标有“ 2019swp”的线,则该线必须为虚线,否则可以使用正常线”。 我一直在阅读详尽的在线教程,但找不到实现此特定目标的方法。我可以看到如何自定义标记和颜色,而不是线条样式。 有什么建议么?非常感谢
答案 0 :(得分:1)
您可以在数据框中添加另一行,其中包含线条样式
df1 = within(df1, {
style = ifelse(date == '2019swp', 'solid', 'dotted')
})
,然后在您的plot_ly
通话中使用此线条样式
plot_ly(data = df1, x=~term, y=~vol, linetype=~style)
有关更多示例,请参见here。
完整代码
library(dplyr)
library(plotly)
df1 <- data.frame(term = c(1,2,3,4, 1,2,3,4, 2, 4),
vol=c(10, 11, 12, 12.3, 9, 9.5, 11, 15, 13, 20),
date=c("2019","2019","2019","2019","2018","2018","2018","2018", "2019swp","2019swp"), stringsAsFactors = F)
df1 = within(df1, {
style = ifelse(date == '2019swp', 'solid', 'dotted')
})
plot_ly(data = df1, x=~term, y=~vol, linetype=~style) %>%
add_trace(type='scatter', mode='lines', color=~date) %>%
layout(title=paste0("Impled Vol Term Structure"),
xaxis=list(title='Term (years)'),
yaxis=list(title='Implied Vol (%)'))