-
Notifications
You must be signed in to change notification settings - Fork 635
Description
If I want to plot a stacked bar chart of mixed positive and negative values, say to recreate a likert plot, the order given in the relevant factor fed to plot_ly's name parameter is not displayed in the chart as one would expect!
Below you find a reprex which does
-
create some sample data
-
plot a bar chart without stacking -> order is fine
-
plot a bar chart with stacking (
barmode = "relative") -> categoryvery goodcomes beforenot so goodwhile I would expect the opposite (same order as inbarmode = "normal")!
As a workaround I could reorder the factor levels before plotting, but then the legend entry order is messed up. Since there's no way to fully customize the order of legend entries, reordering factor levels seems a dead end.
Now this problem might not be specifically R-related, but present in the underlying plotly.js library, I can't tell. Therefore I thought it'd make most sense to report it here and maybe you can bring it up upstream if necessary :)
Brief description of the problem
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
# create example dataset
data_example <- data_frame(question = c("q1", "q1", "q1", "q1",
"q2", "q2", "q2", "q2",
"q3", "q3", "q3", "q3",
"q4", "q4", "q4", "q4"),
category = factor(x = c(0, 1, 2, 3,
0, 1, 2, 3,
0, 1, 2, 3,
0, 1, 2, 3),
labels = c("very bad",
"not so bad",
"not so good",
"very good"),
ordered = TRUE),
percentage = c(-12, -22, 45, 21,
-33, -7, 41, 19,
-50, -27, 13, 10,
-1, -11, 56, 32))
# print example dataset
data_example
#> # A tibble: 16 x 3
#> question category percentage
#> <chr> <ord> <dbl>
#> 1 q1 very bad -12
#> 2 q1 not so bad -22
#> 3 q1 not so good 45
#> 4 q1 very good 21
#> 5 q2 very bad -33
#> 6 q2 not so bad -7
#> 7 q2 not so good 41
#> 8 q2 very good 19
#> 9 q3 very bad -50
#> 10 q3 not so bad -27
#> 11 q3 not so good 13
#> 12 q3 very good 10
#> 13 q4 very bad -1
#> 14 q4 not so bad -11
#> 15 q4 not so good 56
#> 16 q4 very good 32
# plot bar chart without stacking
data_example %>%
plotly::plot_ly(type = "bar",
orientation = "h",
name = ~category,
x = ~percentage,
y = ~question) %>%
plotly::layout(barmode = "normal",
xaxis = list(title = NA,
ticksuffix = " %"),
yaxis = list(title = NA))# plot bar chart with stacking (relative mode)
data_example %>%
plotly::plot_ly(type = "bar",
orientation = "h",
name = ~category,
x = ~percentage,
y = ~question) %>%
plotly::layout(barmode = "relative",
xaxis = list(title = NA,
ticksuffix = " %"),
yaxis = list(title = NA))Created on 2018-11-03 by the reprex package (v0.2.1)

