R plotly:使用ggplotly()时如何保持ggplot2 geom_bar()的宽度参数 [英] R plotly: How to keep width parameter of ggplot2 geom_bar() when using ggplotly()

查看:317
本文介绍了R plotly:使用ggplotly()时如何保持ggplot2 geom_bar()的宽度参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,当使用plotlyggplotly函数将R中的ggplot2条形图(geom_bar)转换为交互式图时,ggplotly强制"这些条粘在一起,甚至如果指定了width参数:

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)

由于某种原因,它也颠倒了ggplot2的默认颜色顺序(尽管将顺序保留在图例中...),但是我可以解决这个问题.

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

任何想告诉ggplotly不要将我的酒吧粘在一起的想法,就像默认设置一样 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将bargap设置为0,您可以通过layout

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

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

由于某种原因,它还会反转ggplot2s的默认颜色顺序 (尽管保持图例中的顺序...),但我可以解决这个问题.

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
}

这篇关于R plotly:使用ggplotly()时如何保持ggplot2 geom_bar()的宽度参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆