使用R中的plotly()对堆叠图中的标签进行对齐。

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

我有一个数据框架

df <- data.frame("QuarterYear" = c("Q1 2019","Q1 2019","Q2 2019","Q2 2019","Q3 2019","Q3 2019","Q3 2019"), "Size" = c("Medium","Small","Large","Medium","Large","Medium","Small"),
                 "percentage" = c(98,2,29,71,13,74,13))

在绘制图形之前,我按照特定的顺序对数据框进行了排序。

quarterYear <- c("Q1 2019","Q2 2019","Q3 2019","Q4 2019")
projSize <- c("Small", "Medium","Large")
df <-  df[order(match(df$QuarterYear, quarterYear), match(df$Size, projSize)), ]

plot_ly(df, x = df$QuarterYear,
        y = df$percentage,
        type = 'bar',
        name = df$Size,
        text = paste(df$percentage,"%"),
        textposition = 'top',
        hoverinfo = 'text',
        hovertext = paste('Size: ', df$Size,
                          '<br> % of Total count: ', paste(df$percentage,"%")),
        color = df$Size) %>%
  layout(yaxis = list(title = "% of Count", zeroline = FALSE, 
                      showline = FALSE, ticksuffix = "%"), barmode = 'stack',hoverlabel = list(bgcolor= 'white')) %>%
  layout(legend = list(orientation = "h",
                       xanchor = "center",
                       x = 0.5,
                       y = -0.13))%>%
  add_annotations(text = paste0(df$percentage, "%"),
                  x = df$QuarterYear,
                  y = unlist(tapply(df$percentage, df$QuarterYear, FUN=cumsum))-(df$percentage/2),
                  showarrow = FALSE) %>%
  layout(xaxis = list(categoryorder = 'array',
                      categoryarray = df$QuarterYear))  

当我对数据进行分类和绘制时,标签变得一团糟。

enter image description here

如何在R中解决这个问题?

先谢谢了!!

r plotly
1个回答
0
投票

将大小变量转换成 "小"、"中"、"大 "级别的因子,然后再重新排列数据框架。

df$Size <- factor(df$Size, levels = c("Small", "Medium","Large"))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.