简体   繁体   English

R plotly:使用ggplotly()时如何保持ggplot2 geom_bar()的宽度参数

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

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: 出于某些原因,在R中使用plotlyggplotly函数将ggplot2条形图( geom_bar )转换为交互式图时,即使指定了width参数, ggplotly “强制”这些条形物粘在一起:

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 ggplot2 s default colors order for some reason (although keeping the order in the legend...), but I can handle this. 由于某种原因,它也颠倒了ggplot2的默认颜色顺序(尽管将顺序保留在图例中...),但是我可以解决这个问题。

Any idea hot to tell ggplotly to not stick my bars together, like the default ggplot2 behavior? 有什么好主意告诉ggplotly不要像默认的ggplot2行为那样把我的酒吧粘在一起吗?

Any idea hot to tell ggplotly to not stick my bars together, like the default ggplot2 behavior? 有什么好主意告诉ggplotly不要像默认的ggplot2行为那样把我的酒吧粘在一起吗?

ggplotly sets bargap to 0 , you could set to your desired value via layout ggplotly设置bargap0 ,你可以设置为通过您的所需值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. 由于某种原因,它也反转了ggplot2s的默认颜色顺序(尽管将顺序保留在图例中...),但是我可以处理。

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
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM