无法使用 ggplotly 函数将我的 ggplot 转换为交互式绘图

failed to convert my ggplot to interactive plot using ggplotly function

我正在制作堆叠条形图。 bar的宽度根据变量w.

设置
library(plotly)
library(tidyverse)

df = data.frame(x = c("a","b","c"),
                w = c(1.2, 1.3, 4),
                y = c(9, 10, 6) )

dat = df %>% mutate(pos = 0.5 * (cumsum(w) + cumsum(c(0, w[-length(w)]))))

g= dat %>% ggplot(aes(x = pos,  y = y, fill = x)) + 
  geom_bar(aes( width = w), stat = "identity") + 
  scale_x_continuous(labels = df$x, breaks =  dat$pos)

ggplotly(g)

ggplot 很好。但是当我尝试使用 ggplotly 将其转换为交互式时,我收到如下错误消息:

Error in nchar(axisObj$ticktext) : 'nchar()' requires a character vector

有谁知道为什么失败了?谢谢。

问题是您的 x-axis 缩放比例。

这应该有效:

library(plotly)
  library(tidyverse)

  df = data.frame(x = c("a","b","c"),
                  w = c(1.2, 1.3, 4),
                  y = c(9, 10, 6) )

  dat = df %>% mutate(pos = 0.5 * (cumsum(w) + cumsum(c(0, w[-length(w)]))))

  g= dat %>% ggplot(aes(x = pos,  y = y, fill = x)) + 
    geom_bar(aes(width = w), stat = "identity") + 
    scale_x_continuous(labels = levels(df$x), breaks =  dat$pos)

  ggplotly(g)

ggplot 似乎将您的 x-axis 标签保留为 factor-levels,而 ggplotly 无法理解。 所以你只需要将它们转换为 character.