【问题标题】:How to convert geom_point(aes()) + geom_vline(aes()) to Plotly?如何将 geom_point(aes()) + geom_vline(aes()) 转换为 Plotly?
【发布时间】:2020-05-03 17:44:15
【问题描述】:

我在网上找到了这个教程,它有助于将 ggplot2 的 geom_abline() 转换为 Plotly 图:https://plotly.com/ggplot2/geom_abline/

看起来我们可以简单地使用ggplotly()进行这样的转换:

library(ggplot2)
library(plotly)

p <- ggplot(data, aes(x=x_val, y=y_val, colour=color_val)) + 
  geom_point() +
  geom_vline(aes(xintercept=xintercept_val), colour=color_val)
ggplotly(p)

但是,我无法使用以下代码将我的 ggplot2 图转换为 Plotly 图:

# notice that both my x_val and xintercept_val are dates.
# here's my ggplot2 code:
gg <- ggplot(data) +
  geom_point(aes(
    x_val,
    y_val,
    color=color_val,
    shape=shape_val
  )) +
  geom_vline(aes(
    xintercept=xintercept_val,
    color=color_val
  ))
ggplotly(gg)

这是我的 ggplot2 图表的屏幕截图(我剪掉了图例):

这是我使用 ggplotly(gg): 的 Plotly 图表的屏幕截图

不知道为什么垂直线没有出现在 Plotly 中。

【问题讨论】:

    标签: r-plotly ggplotly


    【解决方案1】:

    看起来你偶然发现了ggplotly 中的一个错误(也许你应该在github 上提出一个问题)。问题是ggplotly 在内部将日期转换为数字(与分类变量相同)。但是,通过 plotly_json 检查 JSON 表示会发现 geom_vline 中的 xintercepts 未转换。这就是他们不出现的原因。但是,作为一种解决方法,您可以使用 as.numeric() 手动进行转换。

    由于您没有提供数据,我使用了来自plotly website 的简单示例数据集,我在其中添加了一些日期。试试这个:

    dat <- read.table(header=TRUE, text='
          cond xval yval
       control 11.5 10.8
       control  9.3 12.9
       control  8.0  9.9
       control 11.5 10.1
       control  8.6  8.3
       control  9.9  9.5
       control  8.8  8.7
       control 11.7 10.1
       control  9.7  9.3
       control  9.8 12.0
     treatment 10.4 10.6
     treatment 12.1  8.6
     treatment 11.2 11.0
     treatment 10.0  8.8
     treatment 12.9  9.5
     treatment  9.1 10.0
     treatment 13.4  9.6
     treatment 11.6  9.8
     treatment 11.5  9.8
     treatment 12.0 10.6
    ')
    
    dat$xval <- rep(as.Date(paste0("2020-", 1:10, "-01")), 2)
    
    max_date1 <- dat[dat$cond == "control", "xval"][which.max(dat[dat$cond == "control", "yval"])]
    max_date2 <- dat[dat$cond == "treatment", "xval"][which.max(dat[dat$cond == "treatment", "yval"])]
    
    # The basic scatterplot
    p <- ggplot(dat, aes(x=xval, y=yval, colour=cond)) + 
      geom_point()
    
    # Add colored lines for the date of the max yval of each group
    p <- p +
      geom_vline(aes(xintercept=as.numeric(max_date1)), colour="green") + 
      geom_vline(aes(xintercept=as.numeric(max_date2)), colour="lightblue")
    p
    fig <- ggplotly(p)
    
    fig
    

    给我这个情节:

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2020-04-22
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2018-08-06
      相关资源
      最近更新 更多