【问题标题】:How to add vertical lines connecting two sets of points using plotly in R?如何在R中使用plotly添加连接两组点的垂直线?
【发布时间】:2021-01-04 18:25:09
【问题描述】:

我想创建一个绘图,在 R 中使用 plotly 在两组点之间添加垂直线。我知道如何在ggplot2 中执行此操作,并且我知道我可以使用ggplotly 函数将ggplot2 对象转换为plotly 对象。但是,我想了解如何直接使用plotly 来做到这一点。

以下是创建示例数据框的示例代码,并使用ggplot2ggplotly 创建我想要的绘图。

# Load packages
library(tidyverse)
library(plotly)

# Create example dataset
dat <- tibble(
  Group = factor(c(2, 2, 2, 1, 1, 1)),
  Date = as.Date(rep(c("2020-01-01", "2020-01-02", "2020-01-03"), times = 2)),
  value = c(1, 2, 1, 5, 5.5, 6)
)

g <- ggplot(dat, aes(x = Date, y = value, color = Group)) +
  geom_point() +
  scale_color_brewer(type = "qual", palette = "Set1") +
  geom_line(aes(group = Date), color = "black") +
  theme_minimal()

ggplotly(g)

这是另一个示例代码,我尝试使用plotly 创建相同的图。我要做的最后一步是像上一个图一样添加水平线。

plot_ly(dat, x = ~Date, y = ~value, color = ~factor(Group), 
        colors = "Set1",
        type = "scatter", mode = "markers")

【问题讨论】:

    标签: r ggplot2 plot plotly r-plotly


    【解决方案1】:

    这似乎可以

    plot_ly(dat, x = ~Date, y = ~value, color = ~factor(Group), 
            colors = "Set1",
            type = "scatter", mode = "markers") %>%
      add_segments(data=dat,  
                   x = ~Date[Group == 1], 
                   xend= ~ Date[Group == 1], 
                   y = ~value[Group == 1], 
                   yend = ~value[Group ==2],
                   color = ~ Group[Group == 2], 
                   line=list(color="black"), 
                   showlegend=FALSE)  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2022-01-22
      • 2012-06-28
      相关资源
      最近更新 更多