plotly - 按字母顺序排序yaxis

时间:2018-04-13 18:28:54

标签: r plotly

我正在寻找一种按字母顺序按yaxis排序我的阴谋条形图的方法。我尝试了几种方法,但是y的顺序仍然是从z到a,而不是a到z。请帮帮我!

qt <- c("A", "C", "B","B","A", "C", "C")
y <- c("q1", "q2", "q3", "q4", "q5", "q6", "q7")
x1 <- c(20, 10, 15, 15, 20, 10, 15)
x2 <- c(10, 20, 20, 10, 10, 30, 10)
x3 <- c(10, 10, 5, 10, 10, 5, 5)
x4 <- c(20, 25, 25, 35, 55, 40, 35)
x5 <- c(40, 35, 35, 30, 5, 15, 35)
df <- data.frame(qt, y, x1, x2, x3, x4, x5)
df$qt <- factor(df$qt, levels = c("A", "B", "C"))


plot_ly(df) %>%
  add_trace(x = ~x1, y = ~y, marker = list(color = 'rgb(202,0,32)'), type = 'bar', orientation = 'h') %>%
  add_trace(x = ~x2, y = ~y,  marker = list(color = 'rgb(244,165,130)'), type = 'bar', orientation = 'h') %>%
  add_trace(x = ~x3, y = ~y, marker = list(color = 'rgb(223,223,223)'), type = 'bar', orientation = 'h') %>%
  add_trace(x = ~x4, y = ~y, marker = list(color = 'rgb(146,197,222)'), type = 'bar', orientation = 'h') %>%
  add_trace(x = ~x5, y = ~y,  marker = list(color = 'rgb(5,113,176)'), type = 'bar', orientation = 'h') %>%  
  layout(title="mytitle",
         xaxis = list(title = "",
                      showticklabels = TRUE,
                      zeroline = FALSE,
                      domain = c(0.15, 1)),
         yaxis = list(title = "",
                      showticklabels = FALSE,
                      zeroline = FALSE),
         barmode = 'relative',
         paper_bgcolor = 'rgb(248, 248, 255)', plot_bgcolor = 'rgb(248, 248, 255)',
         autosize=T,
         margin = list(l = 150, r = 50, t = 100, b = 50),
         showlegend=F) %>%
  # labeling the y-axis
  add_annotations(xref = 'paper', yref = 'y', x = 0.14, y = df$y,
                  xanchor = 'right',
                  text = df$y,
                  font = list(family = 'Arial', size = 15,
                              color = 'rgb(67, 67, 67)'),
                  showarrow = FALSE, align = 'right')%>%
  #labeling the y-axis (category)
  add_annotations(xref = 'paper', yref = 'qt', x = 0.01, y = df$y,
                  xanchor = 'right',
                  text = df$qt,
                  font = list(family = 'Arial', size = 15,
                              color = 'rgb(67, 67, 67)'),
                  showarrow = FALSE, align = 'right')

我想要完成的主要目标是通过变量 qt (从A到C)来订购。但如果这是不可能的,那么通过 y 排序图也是可取的(从q1到q7)。我的情节看起来像这样: enter image description here

提前谢谢!

0 个答案:

没有答案