按频率对图表垂直条形图排序

时间:2017-07-24 14:55:16

标签: r plotly

我想根据x轴上定量变量的水平对垂直条形图进行排序。

可重复的例子:

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))

plot_ly(
    data = df,
    x = ~a,
    y = ~b,
    type = 'bar',
    orientation = 'h'
) %>%
    layout(
        yaxis = list(
            categoryorder = "array",
            categoryarray = ~a
            )
        )

所以我想要一个垂直条形图,其中y轴向下的排序是:'蓝色','黄色','绿色'和'红色'。我读到了类别订单,这似乎是一个很好的解决方案,但不知怎的,它在实践中不起作用。

1 个答案:

答案 0 :(得分:1)

选项1

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))
df$b = factor(df$b,levels =c("red","green","yellow", "blue") )

plot_ly(
  data = df,
  x = ~a,
  y = ~b,
  type = 'bar',
  orientation = 'h'
) 

选项2

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))

plot_ly(
  data = df,
  x = ~a,
  y = ~b,
  type = 'bar',
  orientation = 'h'
) %>%
  layout(
    yaxis = list(
      categoryorder = "array",
      categoryarray = ~c("red","green","yellow", "blue") )
    )
  )

希望这有帮助! enter image description here