1

I am able to plot a geom_bar as I want but when I try to wrap it with the ggplotly function it does not work. Anyone know a trick to make it work?

library(ggplot2)
library(plotly)

# My df dataset
a=runif(10, min = 0, max = 1)
b=runif(10, min = -1, max = 0)
df=data.frame("p"=c(a,b),
           "g"=rep(c("a","b"),each=10),
           "type"=c(letters[1:10],letters[1:10]))


# Build the g plot
g <- ggplot(df,
             aes(x = as.factor(type), y = p, fill=g)) + 
  geom_bar(data=df[df$g == "a",] ,stat = "identity") + 
  geom_bar( data=df[df$g == "b",] ,stat = "identity") +
  coord_flip() + 
  scale_y_continuous(breaks = seq(-1, 1, 0.25), 
                     labels = paste0(abs(seq(-1, 1, 0.25)))) + 
  xlab("") +
  theme_bw()

# plot it the regular way
g

enter image description here

# plot it the ggplotly way
ggplotly(g)

enter image description here

4

1 回答 1

2

The issue might be with splitting up the two geom_bar calls--you don't actually need to do two of these.

Also note that geom_col() does the same as geom_bar(stat = "identity").

Try this:

g <- df %>%
    ggplot(aes(x = type, y = p, fill = g)) +
        geom_col() +
        coord_flip()

ggplotly(g)

Add back in your scaling, etc--I just dropped everything else for simplicity.

于 2018-05-06T00:12:32.743 回答