[英]plotly bar graph - adding percentages to labels
我正在尝试使用plotly
中的 plotly package 创建一个简单的条形图。 我想在每个条形上方添加标签,但我只能成功添加计数。 是否可以在每个计数旁边添加百分比? 这就是我所拥有的:
fig_valve <- plot_ly(valve_df,
x = ~vlvsz_c,
y = ~count,
type = "bar",
hoverinfo = "x+y")
fig_valve <- fig_valve %>%
add_text(text = ~count,
textposition = "top",
textfont = list(size = 11, color = "black"),
showlegend = FALSE) %>%
layout(title = "",
xaxis = list(title = "Valve Size", showgrid = FALSE),
yaxis = list(title = "Count", showgrid = FALSE),
showlegend = FALSE,
font = t)
我想知道是否可以添加每个类别的百分比。 非常感谢任何建议!
您可以通过text = ~paste0(count, " (", scales::percent(count / sum(count)), ")")
在计数旁边添加百分比,其中我使用scales::percent
进行漂亮的格式化。 使用mtcars
作为示例数据,试试这个:
library(plotly)
library(dplyr)
library(scales)
fig_valve <- mtcars %>%
count(cyl, name = "count") %>%
plot_ly(
x = ~cyl,
y = ~count,
type = "bar",
hoverinfo = "x+y")
fig_valve <- fig_valve %>%
add_text(text = ~paste0(count, " (", scales::percent(count/sum(count)), ")"),
textposition = "top",
textfont = list(size = 11, color = "black"),
showlegend = FALSE) %>%
layout(title = "",
xaxis = list(title = "Valve Size", showgrid = FALSE),
yaxis = list(title = "Count", showgrid = FALSE),
showlegend = FALSE,
font = t)
fig_valve
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.