2017-08-03 132 views
2

以下指南,如ggplot Donut chart我試圖繪製小量規,甜甜圈與中間的標籤,並打算將它們放在地圖上。ggplot2:甜甜圈,如何有條件的顏色填充if_else

如果該值達到一定的閾值,我希望甜甜圈的填充變爲紅色。是否有可能通過if_else實現(這將是最自然的,但它不起作用)。

library(tidyverse) 

df <- tibble(ID=c("A","B"),value=c(0.7,0.5)) %>% gather(key = cat,value = val,-ID) 

ggplot(df, aes(x = val, fill = cat)) + scale_fill_manual(aes,values = c("red", "yellow"))+ 
    geom_bar(position="fill") + coord_polar(start = 0, theta="y") 

ymax <- max(df$val) 
ymin <- min(df$val) 

p2 = ggplot(df, aes(fill=cat, y=0, ymax=1, ymin=val, xmax=4, xmin=3)) + 
    geom_rect(colour="black",stat = "identity") + 
    scale_fill_manual(values = if_else (val > 0.5, "red", "black")) + 
    geom_text(aes(x=0, y=0, label= scales::percent (1-val)), position = position_dodge(0.9))+ 
    coord_polar(theta="y") + 
    xlim(c(0, 4)) + 
    theme_void() + 
    theme(legend.position="none") + 
    scale_y_reverse() + facet_wrap(facets = "ID") 

量表填補手冊值=如果別的....這部分不工作,錯誤說:錯誤if_else(值> 0.5, 「紅」, 「黑色」):對象 'VAL' 不找到。這是我的錯誤,還是存在其他解決方案?

我也意識到我的代碼不是最優的,最初聚集等待更多的變量被包含在圖中,但是我沒有將一個變量堆疊在另一個之上。現在一個變量應該足以表示完成的百分比。我意識到我的代碼對於這個目的是多餘的。你能幫我嗎?

+1

你嘗試過'ifelse()'嗎? 'if_else'不是R函數。 – BLT

+0

@BLT'if_else'是一個dplyr函數。它與'ifelse'類似,但是修復了一些問題。 –

+0

@NicolasPinto我有一箇舊版本,所以當我搜索它沒有出現。謝謝! – BLT

回答

3

一種用於顏色問題的解決方案是在數據首先建立一個變量,然後使用該映射中的情節的顏色:

df <- tibble(ID=c("A","B"),value=c(0.7,0.5)) %>% gather(key = cat,value = val,-ID) %>% 
    mutate(color = if_else(val > 0.5, "red", "black")) 

p2 = ggplot(df, aes(fill=color, y=0, ymax=1, ymin=val, xmax=4, xmin=3)) + 
    geom_rect(colour="black",stat = "identity") + 
    scale_fill_manual(values = c(`red` = "red", `black` = "black")) + 
    geom_text(aes(x=0, y=0, label= scales::percent (1-val)), position = position_dodge(0.9))+ 
    coord_polar(theta="y") + 
    xlim(c(0, 4)) + 
    theme_void() + 
    theme(legend.position="none") + 
    scale_y_reverse() + facet_wrap(facets = "ID") 

其結果將是:

enter image description here