Plotly ggplot stacked bar chart disappear when leg

2019-08-23 01:54发布

I'm not sure why but my stacked bar chart disappears instead of falling to the axis when the legend is clicked. I've attached a screenshot of the example that I copied from the plotly website and the code are as follows:

library(plotly)

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

p <- ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
  geom_bar(stat = "identity")

p <- ggplotly(p)

Stacked Bar Chart disappears when legend is clicked

Can anyone assist me with this?

1条回答
虎瘦雄心在
2楼-- · 2019-08-23 02:38

You can use the plotly API directly, rather than ggplotly, then it works as expected:

plot_ly(DF1) %>%
  add_bars(~Rank, ~value, color=~variable) %>%
  layout(barmode = 'stack')

If you need to also embed a static version of the plot in an R Markdonw document, you can use the export() function to create a static version:

---
title: "Untitled"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

Here's a barchart:

```{r chart}
library(plotly)
library(reshape2)

DF <- read.table(text="Rank F1     F2     F3
                 1    500    250    50
                 2    400    100    30
                 3    300    155    100
                 4    200    90     10", header=TRUE)
DF1 <- melt(DF, id.var="Rank")

p = plot_ly(DF1) %>%
  add_bars(~Rank, ~value, color=~variable) %>%
  layout(barmode = 'stack')
export(p)
```
查看更多
登录 后发表回答