簡體   English   中英

無法使用ggplotly函數將ggplot轉換為交互式繪圖

[英]failed to convert my ggplot to interactive plot using ggplotly function

我正在制作一個堆積的barplot。 條的寬度根據變量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軸縮放比例。

這應該工作:

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似乎ggplot您的x軸標簽保留為ggplotly無法理解的因子水平。 因此,您只需要將它們轉換為character

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM