R plotly: How to keep width parameter of ggplot2 geom_bar() when using ggplotly()

旧街凉风 提交于 2020-01-06 19:35:34

问题


For some reason, when converting in R a ggplot2 bar chart (geom_bar) into an interactive plot using plotly's ggplotly function, ggplotly "forces" the bars to stick together, even if the width parameter is specified:

library(plotly)
library(ggplot2)

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")

ggplotly(p)

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

ggplotly(p)

It also reverses ggplot2s default colors order for some reason (although keeping the order in the legend...), but I can handle this.

Any idea hot to tell ggplotly to not stick my bars together, like the default ggplot2 behavior?


回答1:


Any idea hot to tell ggplotly to not stick my bars together, like the default ggplot2 behavior?

ggplotly sets bargap to 0, you could set to your desired value via layout

ggplotly(p) %>% layout(bargap=0.15)


It also reverses ggplot2s default colors order for some reason (although keeping the order in the legend...), but I can handle this.

Let's get that fixed as well. You can change the order afterwards by flipping the bars and reversing the legend.

gp <- ggplotly(p) %>% layout(bargap = 0.15, legend = list(traceorder = 'reversed'))

traces <- length(gp[['x']][[1]])
for (i in 1:floor(traces / 2)) {
  temp <- gp[['x']][[1]][[i]]
  gp[['x']][[1]][[i]] <- gp[['x']][[1]][[traces + 1 - i]]
  gp[['x']][[1]][[traces + 1 - i]] <- temp
}



来源:https://stackoverflow.com/questions/42813369/r-plotly-how-to-keep-width-parameter-of-ggplot2-geom-bar-when-using-ggplotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!