r - ggplot2: donut ,如何使用 if_else 进行条件颜色填充

标签 r ggplot2 gauge

遵循类似 ggplot Donut chart 的指南我正在尝试绘制小仪表、中间有标签的 donut ,目的是稍后将它们放在 map 上。

如果该值达到某个阈值,我希望 donut 的填充变为红色。是否可以用 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....这部分不起作用,错误显示: if_else(val > 0.5, "red", "black") 中的错误:找不到对象“val”。是我的错误,还是存在其他解决方案?

我还意识到我的代码不是最优的,最初收集等待更多变量包含在图中,但我未能将一个变量堆叠在另一个变量之上。现在一个变量应该足以表明完成的百分比。我意识到我的代码对于这个目的来说是多余的。你能帮我一下吗?

最佳答案

颜色问题的解决方案是首先在数据中创建一个变量,然后使用它来映射绘图中的颜色:

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

关于r - ggplot2: donut ,如何使用 if_else 进行条件颜色填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45490075/

相关文章:

javascript - HIghcharts 衡量不需要的白色边框

iPhone/iPad 圆形强度计控制(含图像)

R 脚本工作正常,但无法在 knit 中运行 - %>% 问题

regex - 在 R 中忽略 strsplit 中的大小写

r - 在 ggplot2 中正确使用 fun.data 和 stat_summary?

r - 如何更改特定线条的粗细和/或在多线图中添加形状?

r - 结合几个 stat_function 行和原始数据点的图例

r - 从头开始查找向量重叠

r - "scale"或 "ruler"在 r 中键入绘图

HIghcharts 4 固体规范最大值