我的条形图有一点问题。 y 轴上的百分比未排序,并停在中间而不是顶部。 这怎么可能? 我也觉得很奇怪,y轴不是100%,停在11.3%
这就是我的图表的样子:
在这张图片中它必须做什么:
这是我的代码:
df1 %>% count(Tijden, Status) %>% mutate(pct=paste0(round(n/sum(n)*100, digits = 1), "%")) %>% plot_ly(x = ~Tijden, y = ~pct, type = 'bar', name = ~Status, text=~pct,textposition = 'auto', textangle = 0 ) %>% layout(yaxis = list(title = "", tickformat = "%"), barmode = 'stack')})
通过添加“%”
pct=paste0(n, "%")
并在plot_ly(x = ~Tijden, y = ~pct, ...)
中使用它,您可以将字符串放入y
中。虽然plotly在绘制条形时似乎理解y是百分比(字符串被视为数字),但当涉及到y轴刻度时,它可能不会理解,其中字符串被视为按字典顺序排序并布局在y轴刻度上的类别y 轴保持原样。
要解决此问题,您可以为放入
y
(浮点)的百分比创建一列,为放入 text
(字符串)的百分比创建一列,并在 plot_ly()
中相应地引用这些变量:
df1 %>%
count(Tijden, Status) %>%
mutate(y = round(n/sum(n)*100, digits = 1), pct = paste0(y, "%")) %>%
plot_ly(x = ~Tijden, y = ~y, type = 'bar', name = ~Status, text=~pct, textposition = 'auto', textangle = 0 ) %>%
layout(yaxis = list(title = "", tickformat = "%"), barmode = 'stack')})