R plotly 仅显示百分比值大于 10 的标签

R plotly show only labels where percentage value is value is above 10

我正在用 R 绘制饼图。 我希望我的标签在图表上,所以我使用 textposition = "inside",对于非常小的切片,这些值不可见。 我正试图找到一种方法来排除这些标签。 理想情况下,我不想在我的地块上打印任何低于 10% 的标签。 设置 textposition = "auto" 效果不佳,因为有很多小切片,而且它使图形看起来很杂乱。 有办法吗?

例如来自 plotly 网站的这些饼图 (https://plot.ly/r/pie-charts/)

library(plotly)
library(dplyr)

cut <- diamonds %>%
  group_by(cut) %>%
  summarize(count = n())

color <- diamonds %>%
  group_by(color) %>%
  summarize(count = n())

clarity <- diamonds %>%
  group_by(clarity) %>%
  summarize(count = n())

plot_ly(cut, labels = cut, values = count, type = "pie", domain = list(x = c(0, 0.4), y = c(0.4, 1)),
        name = "Cut", showlegend = F) %>%
  add_trace(data = color, labels = color, values = count, type = "pie", domain = list(x = c(0.6, 1), y = c(0.4, 1)),
            name = "Color", showlegend = F) %>%
  add_trace(data = clarity, labels = clarity, values = count, type = "pie", domain = list(x = c(0.25, 0.75), y = c(0, 0.6)),
            name = "Clarity", showlegend = F) %>%
  layout(title = "Pie Charts with Subplots")

在 Clarity 的情节中,1.37% 在情节之外,而我希望它们根本不显示。

您必须像这样手动指定扇区标签:

# Sample data
df <- data.frame(category = LETTERS[1:10],
                 value = sample(1:50, size = 10))
# Create sector labels
pct <- round(df$value/sum(df$value),2)
pct[pct<0.1] <- 0  # Anything less than 10% should be blank
pct <- paste0(pct*100, "%")
pct[grep("0%", pct)] <- ""

# Install devtools
install.packages("devtools")

# Install latest version of plotly from github
devtools::install_github("ropensci/plotly")

# Plot
library(plotly)
plot_ly(df, 
        labels = ~category,  # Note formula since plotly 4.0
        values = ~value,  # Note formula since plotly 4.0
        type = "pie",
        text = pct,  # Manually specify sector labels
        textposition = "inside",
        textinfo = "text"  # Ensure plotly only shows our labels and nothing else
        )

查看https://plot.ly/r/reference/#pie了解更多信息...