2016-09-06 78 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 %%」,類別,價值),所以它不顯示任何不必要的信息。 –