【问题标题】:How do I add text in the legend section of a waffle plot in R?如何在 R 中华夫饼图的图例部分添加文本?
【发布时间】:2019-12-02 18:21:13
【问题描述】:

我正在尝试创建一个华夫饼图。我的数据和华夫饼图看起来像这样-

library(waffle)
parts=c("Extraction"=397, "Operculectomy"=11, "Medication"=3)
waffle(parts, row=12, colors=c("#CC0000", "#006600", "#669999"))

我想在该图的图例部分的标签上添加一些文本,如下所示:

提取 (397/413)

包皮切除术 (11/413)

药物治疗 (3/413)

【问题讨论】:

  • 您使用的是哪个包,其中包含waffle 函数?
  • library(waffle)

标签: r legend waffle-chart


【解决方案1】:

根据waffle 包的文档,我不确定您是否可以为waffle 绘图设置很多参数。

但是,您可以通过以下方式修改数据的类别名称:

library(waffle)
parts=c("Extraction"=397, "Operculectomy"=11, "Medication"=3)
names(parts) = paste0(names(parts),"(",parts,"/",sum(parts),")")
waffle(parts, row=12, colors=c("#CC0000", "#006600", "#669999"))

这为您提供了以下图表:

使用 ggplot2 的替代方法

或者,您可以使用来自ggplot2 的geom_tile 来绘制“华夫饼”图。该过程有点不那么简单,但至少您可以享受ggplot2 的完整定制工具。 要获得相同的图表,您可以这样做:

library(ggplot2)
categ_table = c("Extraction"=397, "Operculectomy"=11, "Medication"=3)
df <- expand.grid(y = 1:10, x = 1:(round(sum(categ_table)/10)+1))
df$Category = factor(c(rep(names(categ_table),categ_table),rep(NA,nrow(df)-sum(categ_table))))
df = df[!is.na(df$Category),]

ggplot(df, aes(x = x, y = y, fill = Category)) + 
  geom_tile(color = "white", size = 0.5) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))+
  theme(legend.title = element_blank(),
        panel.background = element_rect(fill = 'white', colour = 'white'),
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank())+ 
  scale_fill_manual(values = c("#CC0000", "#006600", "#669999"),
                    breaks = names(categ_table), 
                    labels = c("Extraction (397/411)","Operculectomy (11/411)", "Medication (3/411)"))

您会得到以下图表:

希望它能回答你的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2022-07-11
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多