2

Following guides like ggplot Donut chart I am trying to draw small gauges, doughnuts with a label in the middle, with the intention to put them later on on a map.

If the value reaches a certain threshold I would like the fill of the doughnut to change to red. Is it possible to achieve with if_else (it would be most natural but it does not work).

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")

Scale fill manual values= if else.... this part does not work, the error says: Error in if_else(val > 0.5, "red", "black") : object 'val' not found. Is it my error, or some other solution exists?

I also realize my code is not optimal, initially gather waited for more variables to be included in the plot, but I failed to stack one variable on top of the other. Now one variable should be enough to indicate the percentage of completion. I realise my code is redundant for the purpose. Can you help me out?

Jacek Kotowski
  • 620
  • 16
  • 49

1 Answers1

3

A solution for the color problem is to first create a variable in the data and then use that to map the color in the plot:

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")

The result would be:

enter image description here

Nícolas Pinto
  • 363
  • 2
  • 14