gpt4 book ai didi

r - 超过100个类别的散布堆积条形图

转载 作者:行者123 更新时间:2023-12-03 16:06:52 24 4
gpt4 key购买 nike

我有一个包含100多个类别的数据集。如果要绘制它,我必须为其编写100多个代码行。以下是密谋官方网站上的示例:

library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

如您所见,如果要绘制100多个动物园,我需要编写 add_trace超过100次,这效率很低。有人知道简化它的方法吗?我尝试使用 for循环,但失败了。

或者,如果有人知道如何使用ggplotly将ggplot转换为交互式格式,那也将解决我的问题。 ggplot生成的图是一个堆叠的分组条形图,其x轴具有10 facet_grid和每个网格中约100个类别。我尝试直接使用ggplotly并将其另存为 .html,但是该图的比例非常奇怪。它看起来应该像一个矩形,宽度大约为40,高度大约为8,但是在 html中,它就像一个正方形,难以辨认。

最佳答案

您可以融化数据,然后如下图所示:

library(data.table)  
library(plotly)

data.table::melt(data, id.vars='Animals') %>%
plot_ly(x = ~Animals, y = ~value, type = 'bar',
name = ~variable, color = ~variable) %>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

这将绘制:

关于r - 超过100个类别的散布堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com