我尽力去理解。首先将萼片长度划分为所需的类别iris_limits
:“1-3”、“3-6”、“6-9”
iris$iris_limits <- cut(iris$Sepal.Length, c(1,3,6,9))
注意:没有萼片长度在 1-3 之间,所以你只有 2 组。
然后,您希望每个萼片长度限制作为 x 轴上的一个单独的条,并且每个单独的萼片长度落入类别中以条形堆叠在一起?您链接到堆叠条的不同颜色的堆叠条形图,这是您想要的吗?
为每个萼片长度创建一个 ID:
iris$ID <- factor(1:nrow(iris))
绘图,color=~ID
如果您想要堆叠条的不同颜色,请设置:
library(plotly)
p <- plot_ly(iris, x = ~iris_limits, y = ~Sepal.Length, type = 'bar', color=~ID) %>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

已编辑对于未堆叠但按 分组的版本iris_limits
,我切换到ggplot2
使用facet_wrap
功能来分隔iris_limits
,然后使用ggplotly
.
gg <- ggplot(iris, aes(x=ID, y=Sepal.Length, fill=iris_limits)) +
geom_bar(stat="identity", position="dodge") +
facet_wrap(~iris_limits, scales="free_x", labeller=label_both) +
theme_minimal() + xlab("") + ylab("Sepal Length") +
theme(axis.text.x=element_blank())
ggplotly(gg)

已编辑:回复:更改图例标题和工具提示显示
要更改图例标题,请使用labs
. 这里还需要更改legend.title
字体大小theme
以适应ggplotly
页边距。
要更改工具提示文本,请添加text
参数以aes
创建所需的字符串,然后定义要在中aes
显示的值。tooltip
ggplotly
gg <- ggplot(iris, aes(x=ID, y=Sepal.Length, fill=iris_limits,
text=paste("Sepal Length:", Sepal.Length, "cm"))) +
geom_bar(stat="identity", position="dodge") +
facet_wrap(~iris_limits, scales="free_x") +
theme_minimal() + xlab("") + ylab("Sepal Length (cm)") +
theme(axis.text.x=element_blank(), legend.title=element_text(size=10)) +
labs(fill="Sepal \nLength (cm)")
ggplotly(gg, tooltip=c("x", "text"))