I'm trying to draw a barplot where bars are colored based on a third "probability" variable. I want to set the colorbar to be fixed to 0:100 and plot different subsets of the data. Everything works well until my subset only contains one observation, then the color does not follow the colorbar any more. Maybe someone can point me in the right direction? Example:
> data <- data.table(name = c("foo", "bar", "bar", "bar"), value = c(10, 15, 40, 35), probability = c(0.9, 0.4, 0.8, 0.3), id = c("one", "two", "three", "four"))
>
> data
name value probability id
1: foo 10 0.9 one
2: bar 15 0.4 two
3: bar 40 0.8 three
4: bar 35 0.3 four
>
> data1 <- data[name == "bar"]
> data2 <- data[name == "foo"]
>
> p1 <- plot_ly(data1,
+ x = ~value,
+ y = ~id,
+ type = "bar",
+ orientation = "h",
+ marker = list(color = ~(probability * 100), colorbar = list(title = "Probability", cmin = 0, cmax = 100))
+ )
>
> p2 <- plot_ly(data2,
+ x = ~value,
+ y = ~id,
+ type = "bar",
+ orientation = "h",
+ marker = list(color = ~(probability * 100), colorbar = list(title = "Probability", cmin = 0, cmax = 100))
+ )
>
> plotly::subplot(p1, p2)
Here is the the resulting plot:
Hello complete stranger,
I think there is actually a bug with Rplotly as vlizana suggested. If you have only one row legend is not working as supposed. Therefore if you add a new row in those cases it will work. And if the row has NA instead of values you will be receiving a warning but it won't appear in the plot.
The code to achieve this is the following one:
data <- data.table(name = c("foo", "bar", "bar", "bar"), value = c(10, 15, 40, 35), probability = c(0.9, 0.4, 0.8, 0.3), id = c("one", "two", "three", "four"))
data1 <- data[name == "bar"]
data2 <- data[name == "foo"]
if(nrow(data2)== 1){
add_data2 <- data2[2L]
add_data2[,1] <- "Delete"
data2 <- rbind(data2, add_data2)
}
p1 <- plot_ly(data1,
x = ~value,
y = ~id,
type = "bar",
orientation = "h",
marker = list(color = ~probability * 100 , colorbar = list(title = "Probability", cmin = 0, cmax = 100, cauto = F))
)
p2 <- plot_ly(data2,
x = ~value,
y = ~id,
type = "bar",
orientation = "h",
marker = list(color = ~probability * 100, colorbar = list(title = "Probability", cmin = 0, cmax = 100, cauto = F))
)
plotly::subplot(p1, p2)