Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 stacked bar with negative values not working with Plotly

Tags:

r

ggplot2

plotly

I tried the code in the answer in this previous thread, 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)

Here is what I'm getting:

enter image description here

If I run plot(plot) then it works fine:

enter image description here

How do I fix the issue in Plotly?

like image 204
milkmotel Avatar asked Mar 31 '26 00:03

milkmotel


1 Answers

For future readers

Nowadays, plotly (I am using 4.8.0) supports stacked barcharts with negative values. In the layout you have to set barmode=relative. Moreover, you can also use the ggplotly functionality posted in the question.

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

Will return:

enter image description here

like image 190
Wilmar van Ommeren Avatar answered Apr 02 '26 12:04

Wilmar van Ommeren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!