我正在开发一个带有运行时 Shiny 的 Flexdashboard,我正在其中绘制圆环图。切片取决于某个变量,有时太小而无法在内部显示百分比,在这种情况下,标签显示在图表外部,如下图所示。
有没有办法保留具有足够大切片的标签/百分比,并去掉由于切片较小而位于外部的标签/百分比?上图中的样子太混乱了,我希望能够看到百分比数据而不必将鼠标悬停在上面。
这是数据和代码
library(plotly)
library(tidyr)
library(dplyr)
InT <- data.frame(Category = c(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB),
`Category Value` = c(172928,1106269,222102,0,1054448,682990,1975937,779346,12398,0,1450944,368130,2493154,4347455,1865752,1443840,692972,61891,6443758,1539659,1659183,2711385,856182,1992250,3722195,2762090,257023,1204422))
plot_ly(InT, labels = ~Category, values = ~`Category Value`) %>%
add_pie(hole = 0.6) %>%
layout(title = "", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE))
一种选择是将带有标签的列添加到数据中,并将低于某个阈值的值的标签设置为 NA。然后可以使用
text=
属性将这些标签添加到您的图表中。
library(plotly)
library(dplyr, warn = FALSE)
library(scales)
InT <- data.frame(
Category = c(LETTERS, "AA", "AB"),
`Category Value` = c(172928, 1106269, 222102, 0, 1054448, 682990, 1975937, 779346, 12398, 0, 1450944, 368130, 2493154, 4347455, 1865752, 1443840, 692972, 61891, 6443758, 1539659, 1659183, 2711385, 856182, 1992250, 3722195, 2762090, 257023, 1204422),
check.names = FALSE
)
InT <- InT |>
mutate(
percent = `Category Value` / sum(`Category Value`),
text = ifelse(
percent > .01,
scales::percent(percent, accuracy = .1),
NA
)
)
xaxis <- yaxis <- list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE)
plot_ly(InT, labels = ~Category, values = ~`Category Value`, text = ~text) %>%
add_pie(
hole = 0.6,
textinfo = "text",
hoverinfo = "label+value+percent"
) %>%
layout(
title = "",
showlegend = FALSE,
xaxis = xaxis,
yaxis = yaxis
)