R中实线和虚线图的混合

时间:2019-11-26 06:07:30

标签: r ggplot2 plotly

我希望制作一条实线(实际数据),然后以虚线(投影数据)绘制的图形。

类似这样,但在plotly中:

enter image description here

library(tidyverse)
library(plotly)

#data
df <- tibble(type = c("Actual", "Actual", "Actual", "Projected", "Projected", "Projected"),
             year = c(2016, 2017, 2018, 2019, 2020, 2021),
             values = c(2, 2, 3, 4, 5, 4))

#ggplot version
ggplot(df %>% filter(type == "Actual"), aes(year, values)) +
  geom_line() + #actual data
  geom_line(data = df %>% filter(year >= 2018), aes(year, values), linetype = "dashed") + 
  geom_point(data = df %>% filter(type == "Actual"), aes(year, values), size = 3) +  
  geom_point(data = df %>% filter(type == "Projected"), aes(year, values), size = 3)

#non working plotly
plot_ly(df %>% filter(type == "Actual"), x = ~year, y = ~values, type = 'scatter', mode = 'lines+markers') %>%
  add_trace(df %>% filter(type == "Projected"), x = ~year, y = ~values, name = 'trace 1', dash = 'dot') %>%
  layout(xaxis = list(title = 'Year'),
         yaxis = list (title = 'Value')) %>%
  layout(yaxis = list(rangemode = "tozero"))

我知道我可以使用ggplotly,但是plotly中的工具提示对于我要执行的操作来说更好。

关于将'dash'与'scatter'对象一起使用的警告消息,但我只是按照教程页面上的示例进行操作:https://plot.ly/r/line-charts/

  

警告消息:“散布”对象不具有以下属性:“破折号”

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

library(plotly)
library(dplyr)

plot_ly() %>%
  # a trace with all the data, dashed
  add_trace(data = df,  x = ~year, y = ~values,
            name = 'Projected', type = 'scatter', mode = 'lines+markers',
            line = list(shape = 'linear', color = 'black', width= 4, dash = 'dash'))%>%
  # a trace that overwrites the actual
  add_trace(data = df %>% filter(type == "Actual"),  x = ~year, y = ~values,
            name = 'Actual', type = 'scatter', mode = 'lines+markers',
            line = list(shape = 'linear', color = 'black', width= 4, dash = 'solid'))%>%
  # remove legend
  layout(showlegend = FALSE)

enter image description here