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

时间:2016-09-06 13:26:14

标签: r pie-chart labels plotly

我正在用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%不在情节之内,而我希望它们根本不显示。

1 个答案:

答案 0 :(得分:3)

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

# 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了解详情......