r - 具有负值的ggplot2堆积条不适用于Plotly

标签 r ggplot2 plotly

我尝试了前一个线程中答案中的代码,ggplot2 and a Stacked Bar Chart with Negative Values .

dat <- read.table(text = "   Division Year OperatingIncome
1  A  2012           11460
  2  B  2012            7431
  3  C  2012           -8121
  4  D  2012           15719
  5  E  2012             364
  6  A  2011           12211
  7  B  2011            6290
  8  C  2011           -2657
  9  D  2011           14657
  10 E  2011            1257
  11 A  2010           12895
  12 B  2010            5381
  13 C  2010           -2408
  14 D  2010           11849
  15 E  2010             517",header = TRUE,sep = "",row.names = 1)

dat1 <- subset(dat,OperatingIncome >= 0)
dat2 <- subset(dat,OperatingIncome < 0)
plot <- ggplot() + 
  geom_bar(data = dat1, aes(x=Year, y=OperatingIncome, fill=Division),stat = "identity") +
  geom_bar(data = dat2, aes(x=Year, y=OperatingIncome, fill=Division),stat = "identity") +
  scale_fill_brewer(type = "seq", palette = 1)
ggplotly(plot)

这是我得到的:

enter image description here

如果我运行 plot(plot) 然后它工作正常:

enter image description here

如何解决 Plotly 中的问题?

最佳答案

对于 future 的读者

如今,plotly(我正在使用 4.8.0)支持具有负值的堆叠条形图。在 layout 中,您必须设置 barmode=relative。此外,您还可以使用问题中发布的 ggplotly 功能。

plot_ly(dat, y=~OperatingIncome, x=~Year, type='bar', name=~Division, color =~Division, 
        colors='Blues', marker=list(line=list(width=1, color='lightgray'))) %>% 
  layout(barmode = 'relative')

将返回:

enter image description here

关于r - 具有负值的ggplot2堆积条不适用于Plotly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41768327/

相关文章:

python - 在 Windows 10 上的 R Studio 中安装和运行 Tensorflow 的噩梦

r - 美学必须是长度为 1 或与数据问题相同的长度

r - 如何使带有 geom_jitter 的散点图可重现?

r - ggplot 颜色以具有预定义调色板的其他列为条件

python - 如何修复已弃用的 plotly.plotly 模块

r - 如何避免 data.table 中的优化警告

r - 如何调整 R 中脊线图的带宽

python - 如何按组为散点图分配颜色?

r - 通过因子 plotly R 绘制和跟踪相同的颜色

r - 如何在 R 中用数字向量表示多项式