我尽力去理解。首先将萼片长度划分为所需的类别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')
EDITED对于不堆叠但分组的版本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
in 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"))