如何在不影响 Plotly R 中条形图顺序的情况下反转图例顺序?

问题描述 投票:0回答:1

我正在使用 R 中的 Plotly 创建堆积条形图,图例中项目的顺序与我想要的顺序相反。

library(dplyr)
library(plotly)
library(forcats)

set.seed(1)

df <- data.frame(
  institution = c('Four-year colleges', 'Two-year colleges', 'Nonprofit organizations', 'Other'),
  percentage = c(27,22,30,31)
)

df <- df %>%
  mutate(institution = fct_reorder(institution, percentage, .desc = TRUE))

color_palette = c('#245075', '#B03E61', '#BD4C42', '#4B7F60')

fig2 <- df
fig2 <- fig2 %>% plot_ly(
  x = ~percentage, y = ~factor(1),  type = 'bar',
  color = ~institution,
  colors = color_palette,
  text = ~paste0(percentage, '%'),
  textfont = list(color = 'white'), 
  height = 170
)

fig2 <- fig2 %>% layout(
  yaxis = list(
    title = '',
    showticklabels = FALSE,
    showgrid = FALSE,
    zeroline = FALSE,
    showline = FALSE
  ),
  xaxis = list(
    title = '',
    showticklabels = FALSE,
    showgrid = FALSE,
    zeroline = FALSE,
    showline = FALSE
  ),
  barmode = 'stack',
  showlegend = TRUE,
  legend = list(orientation = 'h')
)
fig2 <- fig2 %>%config(displayModeBar = FALSE)
fig2

堆积条形图

我尝试颠倒因子顺序。虽然这修复了图例的顺序,但它会导致堆叠条形图和颜色反转。

df <- df %>% mutate(institution = fct_reorder(institution, percentage, .desc = FALSE))

堆积条形图2

r plotly bar-chart legend stacked-bar-chart
1个回答
0
投票

刚刚在这个论坛中找到它修复情节图例顺序

这很荒谬,因为在情节文档中没有任何地方谈论traceorder。

legend = list(orientation = 'h', traceorder = 'normal')
© www.soinside.com 2019 - 2024. All rights reserved.