Plotly R:无法将段添加到有序条形图

Plotly R: can't add segment to a ordered bar plot

基本上,我有这个 dataframe:

# dataframe
df2 = data.frame(value = c(9, 2, 7, 5, 6),
                 key = c('ar', 'or', 'br', 'gt', 'ko'))

这就是我需要的情节。我正在使用 reorder,因为我知道这是正确排序金条的好方法。

library(tidyverse)
df2 %>% ggplot() + 
  geom_col(aes(reorder(key, -value), value), fill = 'grey') + 
  geom_hline(yintercept = 4)

CORRECT PLOT


我试图在 plotly 中执行此操作,但每次我使用 reorder 时,它都无法正常工作。

此外,我希望 segment 从第一个柱的最 左侧 开始,并在最 右侧 结束。 =38=] 最后一个小节。

# using reorder to order the bars doesn't work!
df2 %>% 
  plot_ly(x = ~reorder(key, -value), # <- here
          y = ~value,
          color = I('grey'),
          type = 'bar') %>% 
  add_segments(x = 'ar', xend = 'or',
               y = 4, yend = 4, 
               color = I('black'))

WRONG PLOT

这里有什么提示吗?

问题是添加段会破坏条形图的顺序。但是,根据您的示例调整此 ,您可以通过 layout:

手动设置 x 轴的顺序来实现您想要的结果
library(plotly)

xform <- list(categoryorder = "array",
              categoryarray = levels(reorder(df2$key, -df2$value)))

df2 %>% 
  plot_ly(x = ~key,
          y = ~value,
          color = I('grey'),
          type = 'bar') %>% 
  add_segments(x = 'ar', xend = 'or',
               y = 4, yend = 4, 
               color = I('black')) %>%
  layout(xaxis = xform)

要解决您的第二个问题:调整此 您可以通过将 key 变量转换为数字并通过 layout 设置轴标签来切换到连续刻度:

df2 %>%
  plot_ly(
    x = ~ as.numeric(reorder(key, -value)),
    y = ~value,
    color = I("grey"),
    type = "bar"
  ) %>%
  add_segments(
    x = .6, xend = 5.4,
    y = 4, yend = 4,
    color = I("black")
  ) %>%
  layout(
    xaxis = list(
      ticktext = levels(reorder(df2$key, -df2$value)),
      tickvals = seq_along(df2$key),
      tickmode = "array",
      range = c(0.5, 5.5)
    )
  )