如何在组内对 R Plotly 分组条形图进行排序?
How to sort an R Plotly grouped bar chart within groups?
可重现的例子:
library(data.table)
library(plotly)
df <- data.table(
x = c(rep("positive", 4), rep("neutral", 4), rep("none", 4), rep("negative", 4)),
y = rep(c("one", "two", "three", "four"), 4),
percent = c(
38.9, 33.3, 8.7, 19.1, 29.4, 29.6, 21.6, 19.4,
37.4, 24.9, 16.6, 21.1, 27.8, 34.5, 14.4, 23.2
)
)
# Sort rows based on 'percent' within each subgroup in 'y', preserving grouping in 'x'
df <- df[order(x, -percent)]
plot_ly(
df,
x = ~percent,
y = ~x,
color = ~y,
type = "bar",
orientation = "h",
hovertemplate = "Group: %{fullData.name} <br> Percent: %{x}% <extra></extra>",
opacity = 0.9,
hoverlabel = list(
align = "left"
)
) %>%
layout(
font = list(
family = "Open Sans",
size = 13
),
xaxis = list(
title = "",
showticklabels = TRUE
),
yaxis = list(
title = ""
)
)
这将生成以下图表:
如何在每个组中将条形从最高到最低(百分比)排序?这在R级别可能吗?我尝试在layout
中指定categoryorder and categoryarray参数,但似乎没有生效?谢谢
所以这就是我要为使用 ggcharts
库和 bar_chart
:
的分面解决方案所做的
p <- ggcharts::bar_chart(
df,
y,
percent,
fill = x,
facet = x,
)
p
基于 Andrew Ingalls 的解决方案和 Dan Adams 在评论中的建议的最小解决方案:
library(ggcharts)
ggcharts::bar_chart(
df,
y,
percent,
fill = x,
facet = x,
) |>
plotly::ggplotly()
也用 plotly::renderPlotly()
测试过。
可重现的例子:
library(data.table)
library(plotly)
df <- data.table(
x = c(rep("positive", 4), rep("neutral", 4), rep("none", 4), rep("negative", 4)),
y = rep(c("one", "two", "three", "four"), 4),
percent = c(
38.9, 33.3, 8.7, 19.1, 29.4, 29.6, 21.6, 19.4,
37.4, 24.9, 16.6, 21.1, 27.8, 34.5, 14.4, 23.2
)
)
# Sort rows based on 'percent' within each subgroup in 'y', preserving grouping in 'x'
df <- df[order(x, -percent)]
plot_ly(
df,
x = ~percent,
y = ~x,
color = ~y,
type = "bar",
orientation = "h",
hovertemplate = "Group: %{fullData.name} <br> Percent: %{x}% <extra></extra>",
opacity = 0.9,
hoverlabel = list(
align = "left"
)
) %>%
layout(
font = list(
family = "Open Sans",
size = 13
),
xaxis = list(
title = "",
showticklabels = TRUE
),
yaxis = list(
title = ""
)
)
这将生成以下图表:
如何在每个组中将条形从最高到最低(百分比)排序?这在R级别可能吗?我尝试在layout
中指定categoryorder and categoryarray参数,但似乎没有生效?谢谢
所以这就是我要为使用 ggcharts
库和 bar_chart
:
p <- ggcharts::bar_chart(
df,
y,
percent,
fill = x,
facet = x,
)
p
基于 Andrew Ingalls 的解决方案和 Dan Adams 在评论中的建议的最小解决方案:
library(ggcharts)
ggcharts::bar_chart(
df,
y,
percent,
fill = x,
facet = x,
) |>
plotly::ggplotly()
也用 plotly::renderPlotly()
测试过。