2017-07-26 58 views
2

我面临一些与ggplot2和plotly问题。当使用ggplot2创建条形图并将其传递给函数ggplotly时,取消选择变量时,条形图将处于半空状态。该图不像示例here条形图在plotly *苍蝇*时取消选择变量

例子:

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在以下运行:

> 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 

谢谢!

回答

1

我认为问题在于ggplot2和plotly之间的相互作用。 直接使用plot_ly功能

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

谢谢你,似乎是这样。我更喜欢在ggplot2中创建情节,但您的解决方案解决了我的问题。 – Pierre