1

I'm making a stacked barplot. The width of the bar is set according to variable 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)

The ggplot is fine. But when I tried to convert it to interactive using ggplotly, I got error message as below:

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

Does anyone know why this failed? Thanks.

1 Answer 1

3

The Problem is your x-axis scaling.

This should work:

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 seems to keep your x-axis labels as factor-levels which ggplotly doesn't understand. So you just need to convert them to character.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.