Reputation: 11833
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.
Upvotes: 1
Views: 559
Reputation: 1800
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
.
Upvotes: 3