2016-09-06 83 views
0

我正在制作一个饼图在R中作图。 我希望我的标签位于图表上,因此我使用textposition = "inside",对于非常小的切片这些值不可见。 我想找到一种方法来排除这些标签。 理想情况下,我希望不要在我的地块上打印任何低于10%的标签。 设置textposition = "auto"不能很好地工作,因为有很多小切片,并且它使图形看起来非常混乱。 有没有办法做到这一点?R只能显示标签,其中百分比值是10以上

例如从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") 

在情节的清晰度1.37%,这是扇形图的情节之外,而我想他们不会显示在所有。

+0

欢迎StackOverflow上。请提供一个[MCVE] –

回答

2

你必须手工指定,像这样的标签业:

# 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更多信息...

+0

谢谢,这是一个好主意,但是我的问题仍然存在,因为我已经在hoverinfo中使用了“text”:hoverinfo =“text”,text = sprintf(“%s:%s %%”,类别,价值),所以它不显示任何不必要的信息。 –