我正在尝试使用R中的plotly
包创建一个简单的条形图。我想在每个条形上方添加标签,但是我只能成功添加计数。是否可以在每个计数旁边添加百分比?这就是我所拥有的:
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