2
votes

Im facing some issues with ggplot2 and plotly. When creating a bar chart with ggplot2 and pass it into the function ggplotly the bars are mid air when deselecting variables. The graph is not behaving as the examples here .

Example:

library(ggplot2)
library(reshape2)
library(plotly)

df1 <- data.frame("Price" = rnorm(3, mean = 100, sd = 4), 
                 "Type" = paste("Type", 1:3))

df2 <- data.frame("Price" = rnorm(3, mean = 500, sd = 4), 
                  "Type" = paste("Type", 1:3))

df <- rbind(df1, df2)

df$Dates <- rep(c("2017-01-01", "2017-06-30"), 3)

df <- melt(df, measure.vars = 3)

p <- ggplot(df, aes(fill=Type, y=Price, x=value)) + 
  geom_bar(stat="identity", position = "stack")

ggplotly(p)

G1

enter image description here

Im running on following:

> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Swedish_Sweden.1252  LC_CTYPE=Swedish_Sweden.1252    LC_MONETARY=Swedish_Sweden.1252 LC_NUMERIC=C                   
[5] LC_TIME=Swedish_Sweden.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] zoo_1.8-0          dygraphs_1.1.1.4   plotly_4.7.0.9000  reshape2_1.4.2     ggplot2_2.2.1.9000 lubridate_1.6.0    readxl_1.0.0

Thanks!

1

1 Answers

1
votes

I think the problem is in the interaction between ggplot2 and plotly. Use plot_ly function directly

p <- plot_ly(df, x = ~value, y = ~Price, type = 'bar',split=~Type) %>%
  layout(yaxis = list(title = 'Count'), barmode = 'stack')
p