Reputation: 653
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:
Upvotes: 5
Views: 2481
Reputation: 21
It seems that as per today it has changed a little:
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)
)
library(plotly)
before:
plot_ly(dat1, type = "bar", x=Score, y=Attributes, group=Item, orientation="h")
now what it worked for me:
plot_ly(type = "bar", x=dat1$Score, y=dat1$Attributes, split=dat1$Item, orientation="h")
Upvotes: 0
Reputation: 31452
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")
Upvotes: 5