r - 尝试更改 R 中 ggplot 图的颜色

标签 r colors ggplot2 donut-chart

我正在尝试复制下图中的 donut chart 。

Attempting to replicate

我已经完成了除实际着色之外的所有内容,并且对我在 ggplot 的 scale_colour_manual 部分中做错了什么感到困惑。

这是我用于 ggplot 的代码:

    ggplot(base_ind_zones) + 
    geom_rect(aes(fill = base_zones, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
    geom_rect(aes(fill = ind, ymax=ymax, ymin=ymin, xmax=3, xmin=2)) +  
    xlim(c(0, 4)) + 
    theme(aspect.ratio=1) +
    coord_polar(theta = "y", start = ((2*3.14)/3)) +
    theme(panel.grid=element_blank()) +
    theme(axis.text=element_blank()) +
    theme(axis.ticks=element_blank()) +
    scale_colour_manual(breaks = c("A", "B", "C", "D"),
    values = c(adjustcolor("blue", alpha.f = 0), "firebrick4", "grey99", "skyblue1"))

和一个样本数据集:
    base_ind_zones <- base_ind_zones = data.frame(category=c("A", "B", "C", "D"),
    base_zones=c(33, 44, 12, 11),
    ind=c(33, 44, 2, 21))

    #Needed to determine the ymin and ymax for ggplot
    base_ind_zones$fraction = base_ind_zones$ind / sum(base_ind_zones$ind)
    base_ind_zones$ymax = cumsum(base_ind_zones$fraction)
    base_ind_zones$ymin = c(0, head(base_ind_zones$ymax, n = -1))

Current output

在添加 scale_colour_manual 之前,我得到了上面的 donut chart 。添加 scale_colour_manual 后,颜色没有变化。我需要对 scale_colou_manual 进行哪些更改才能更改颜色?如果我没有走在正确的轨道上,我真的很感激任何形式的指导。提前致谢!

最佳答案

base_ind_zones <- data.frame(category=c("A", "B", "C", "D"),
                                          base_zones=as.character(c(33, 44, 12, 11)),
                                          ind=as.character(c(33, 45, 2, 21)),
                         stringsAsFactors = FALSE)

#Needed to determine the ymin and ymax for ggplot
base_ind_zones$fraction = as.numeric(base_ind_zones$ind) /
  sum(as.numeric(base_ind_zones$ind))
base_ind_zones$ymax = cumsum(base_ind_zones$fraction)
base_ind_zones$ymin = c(0, head(base_ind_zones$ymax, n = -1))

ggplot(base_ind_zones) + 
  geom_rect(aes(fill = base_zones, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
  geom_rect(aes(fill = ind, ymax=ymax, ymin=ymin, xmax=3, xmin=2)) +  
  xlim(c(0, 4)) + 
  theme(aspect.ratio=1) +
  coord_polar(theta = "y", start = ((2*3.14)/3)) +
  theme(panel.grid=element_blank()) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  scale_fill_manual(breaks = c("A", "B", "C", "D"),
              values = c("33"="white", "44"="firebrick4", "12"="white", 
                         "11"="skyblue1", "2"="black", "21"="white", "45"="black"))

enter image description here

关于r - 尝试更改 R 中 ggplot 图的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34307477/

相关文章:

php - 使用 PHP 检测图像的颜色

JavaScript 在单击时更改 div "array"的颜色?

javascript - 对右偏数据使用正确的色标

r - 以百分比计算字符串相似度

在 dplyr 中从字符重新编码为因子中的数字

r - 如何在 facet_wrap 中使用 label_wrap_gen 和 as_labeller

r - facet_grid label_both 将标签文本动态分面变量包装在 Shiny 的图中

R ggplot分组并绘制多条线

r - R 中具有 95% 置信区间的箱线图

r - 显示使用 Rscript 执行的输入