Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotly grouped bar chart does not show negative values

Background: I'm working on updating a small Shiny application to use plotly instead ggplot2 in order to make the chart interactive. (Note: I'm relatively new to R).

Problem: I'm using a grouped bar chart that sometimes has a mix of positive and negative values. When using ggplot2 and renderPlot, my chart works as expected. However, when using plotly & renderPlotly the bars on the chart all show as positive. When I hover over the bars, I can see the negative values.

Sample code:

dat1 <- data.frame(
  Item = factor(c("Female","Female","Male","Male")),
  Attributes = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
  Score = c(13.53, 16.81, -16.24, 17.42)
)

build_chart <- function(df){

  p <- ggplot(df, aes(factor(Attributes), Score, fill=Item)) +
    geom_bar(stat="identity", position="dodge") +
    coord_flip()

  p
}

build_chart(dat1)
ggplotly(build_chart(dat1))

Illustration:

Desired result (ggplot2):

ggplot2

plotly result:

plotly

like image 666
KingOfTheNerds Avatar asked Aug 24 '16 23:08

KingOfTheNerds


1 Answers

I see a lot of occasions where ggplotly() gives unexpected results. It is an imperfect interface to plotly, that works well sometimes, but all too often glitches. You can build the graph directly in plotly quite easily. Using the plotly API directly, rather than through ggplot also has the advantage that it gives you access to many chart attributes that can't be controlled with ggplot

plot_ly(dat1, type = "bar", x=Score, y=Attributes, group=Item, orientation="h") 

enter image description here

like image 94
dww Avatar answered Sep 23 '22 22:09

dww