I want to create a stacked bar chart in R and plotly using iris dataset. In the x-axis, I want to set limits like iris_limits below in the code and the y-axis should contain all the Sepal.Length values which fit into these ranges. I want to pass the values as a single vector. Also, if the limits can be made dynamic by understanding the range of the Sepal.Length instead of hard coding it, please help. I have written a basic script with values to give you an idea. Thanks.
library(plotly)
iris_limits <- c("1-4", "4-6", "6-8")
sepal <- c(2.4,5.4,7.1)
data <- data.frame(iris_limits, sepal)
p <- plot_ly(data, x = ~iris_limits, y = ~sepal, type = 'bar', name =
'Sepal') %>%
layout(yaxis = list(title = 'Count'), barmode = 'group')
p
I tried my best to understand. First dividing the sepal length to the desired categories
iris_limits
: "1-3","3-6","6-9"Note: no sepal length is in between 1-3, so you only have 2 groups.
Then you want each sepal length limit as a separate bar on the x axis, and each individual sepal length falling into category to be bar stacked onto each other? You linked to a stack bar chart with varying color for the stacked bars, is this what you want?
Create an ID for each sepal length:
Plot, set
color=~ID
if you want different colors for the stacked bars:EDITED For version that is not stacked but grouped by
iris_limits
, I switched toggplot2
to make use offacet_wrap
functionality to segregate byiris_limits
, then useggplotly
.EDITED: Re: Changing legend title and tooltip display
To change the legend title, use
labs
. Here it was also necessary to change thelegend.title
font size undertheme
to fit theggplotly
margins.To change the tooltip text, add
text
parameter toaes
to create desired character string, then defineaes
values to be displayed intooltip
inggplotly
.Try using
cut
:The grouping details: