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):
plotly result:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With