Gal*_*huk 3 label r pie-chart 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")
Run Code Online (Sandbox Code Playgroud)
在 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
)
Run Code Online (Sandbox Code Playgroud)
查看https://plot.ly/r/reference/#pie了解更多信息...
| 归档时间: |
|
| 查看次数: |
7454 次 |
| 最近记录: |