繁体   English   中英

在ggplot2中与facet一起创建一个华夫饼图

[英]Creating a waffle plot together with facets in ggplot2

有没有简单的方法可以在ggplot2中与facet结合创建华夫饼图,或者与华夫饼包一起梳理?

例如,用100个方格替换下面的每个条形代表1%。

ggplot(mtcars, aes(x = factor(vs), y = hp, fill = as.factor(carb))) +
  geom_bar(stat = 'identity', position = 'fill') +
  facet_wrap('gear')

我不确定我是否会使用stat_waffle() / geom_waffle()但你可以使用包中的逻辑来做同样的事情:

library(hrbrthemes)
library(tidyverse)

我们需要计算百分比,然后让每个组总和达到100,所以我们需要一个辅助函数,它已经在SO上存在了一段时间:

smart_round <- function(x, digits = 0) { # somewhere on SO
  up <- 10 ^ digits
  x <- x * up
  y <- floor(x)
  indices <- tail(order(x-y), round(sum(x)) - sum(y))
  y[indices] <- y[indices] + 1
  y / up
}

waffle包装中有2个“魔力”。 一位是算法的一部分,它只是复制因子分量正确的次数。 我们将以下函数逐行应用于我们将要制作的数据框:

waffleize <- function(xdf) {
  data_frame(
    gear_vs = rep(xdf$gear_vs, xdf$pct),
    carb = rep(xdf$carb, xdf$pct)
  )
}

现在我们需要:

  • 为你的例子做同样的数学ggplot2
  • 计算组的百分比
  • 将%转换为100的部分,使每组甚至达到100
  • 因为我们不能在一个面板中有两个不同的geom_tile() s,我们需要破解一个方面名称,它将做同样的事情
  • 小组说,黑客
  • 复制每一行pct
  • 确保订购正确
  • 加入一个10x10 x / y网格,以获得我们将拥有的多个方面(在本例中为6); 这是华夫饼包装的另一部分“神奇”
  • 画瓷砖

^^转化为👇(这条管道链是凌晨一点长,我的舒适度,但“它的工作原理”):

count(mtcars, gear, vs, carb, wt=hp) %>% 
  group_by(gear, vs) %>% 
  mutate(pct = n/sum(n)) %>% 
  mutate(pct = (smart_round(pct, 1) * 100L) %>%  as.integer()) %>% 
  select(-n) %>% 
  ungroup() %>% 
  mutate(carb = as.character(carb))  %>% 
  mutate(gear_vs = sprintf("%s-%s", gear, vs)) %>% 
  select(gear_vs, carb, pct, -gear, -vs) %>% 
  rowwise() %>% 
  do(waffleize(.)) %>% 
  ungroup() %>% 
  arrange(gear_vs, carb) %>% 
  bind_cols(
    map_df(seq_len(length(unique(.$gear_vs))), ~expand.grid(y = 1:10, x = 1:10))
  ) %>% 
  ggplot(aes(x, y)) + 
  geom_tile(aes(fill=carb), color="white", size=0.5) +
  ggthemes::scale_fill_tableau() +
  facet_wrap(~gear_vs) +
  coord_equal() +
  labs(x=NULL, y = NULL) +
  hrbrthemes::theme_ipsum_rc(grid="") +
  theme(axis.text=element_blank()) 

在此输入图像描述

@hrbrmstr优秀答案的一点点补充(感谢您制作包并与我们共享代码!)。 我也一直在努力制作这样的图,因为我认为这是比饼图进行比较时更好的可视化数据的方法。 我的华 饼图理念与现有的解决方案( 华夫饼干ggwaffle )有三种不同:

  1. 华夫饼应始终以纵横比为1的10x10%网格呈现,如所需的OP问题和@hrbrmstr答案。 这使得阅读百分比更容易。
  2. 华夫饼应该从左到右(读取方向)和从底部向上(如玻璃中的水,与现有解决方案不同)填充。 这使得阅读百分比对我来说更自然。
  3. 可以将1%的细胞分开以适应分数百分比。 当使用完整百分比时,贡献<1%的组消失,但在我使用这些图的应用程序中,缺少的组具有与(0,1)组不同的含义。

因为我花了相当长的时间来解决上面提到的问题,所以我发布了我的解决方案。 代码背后的“神奇”(即方法)已从现有软件包中清除。 我希望这可以帮助某人并推动华夫饼图的发展。 我真的认为这些图表具有数据可视化的潜力。 将这些函数实现为ggplot2 proto对象会很好,但在尝试之后我不得不放弃。 我不明白proto系统能够为它编写代码。 我添加了我计​​划添加的所有功能后,我只需复制我打算包含在我的R包中的代码(计划是使华夫饼图与scatterpie类似)。 请注意,下面的许多代码都是为了让华夫饼变得漂亮。 实际上烘烤华夫饼的部分并不复杂,并且在@hrbrmstr答案中得到了很好的解释。

运行示例所需的函数:

library(dplyr)
library(ggplot2)

#' @title Convert line sizes measured as points to ggplot line sizes
#' @description Converts line sizes measured as points (as given by most programs such as Adobe Illustrator etc.) to ggplot font sizes
#' @param x numeric vector giving the lines sizes in points
#' @return Returns a numeric vector of lenght \code{x} of ggplot line sizes
#' @keywords internal
#' @export
#'
LS <- function(x) x/2.13

#' @title Round values preserving total sums
#' @description The function rounds values preserving total sums
#' @param x numeric vector of values to be rounded
#' @param digits integer indicating the number of decimal places. See \code{\link[base]{round}}.
#' @return Returns a numeric vector.
#' @author The function is written as a communal effort. Main authors are \href{https://stackoverflow.com/questions/32544646/round-vector-of-numerics-to-integer-while-preserving-their-sum}{josliber} and \href{https://www.r-bloggers.com/round-values-while-preserve-their-rounded-sum-in-r/}{BioStatMatt}.
#' @keywords internal
#' @family waffle
#' @export

round_preserve_sum <- function(x, digits = 0) {
  up <- 10 ^ digits
  x <- x * up
  y <- floor(x)
  indices <- tail(order(x-y), round(sum(x)) - sum(y))
  y[indices] <- y[indices] + 1
  y / up
}  # from https://www.r-bloggers.com/round-values-while-preserve-their-rounded-sum-in-r/

#' @title Prepare data for waffle plots
#' @description Manipulates a data frame ready for plotting with the \code{\link{waffle_chart}} function.
#' @param dt data frame containing the data which should be transformed
#' @param fill character specifying the column name which should be used as fill for the waffle plot.
#' @param value character specifying the column name which contains values of the \code{fill} variable.
#' @param composition logical indicating whether a compositional waffle (i.e. fill adds up to 100\%) should be created. If \code{FALSE}, waffle cells will be scaled to \code{max_value} and missing cells filled with an "empty" category.
#' @param max_value numerical giving the value to which waffle cells should be scaled to, if \code{composition = FALSE}.
#' @param digits integer indicating the number of decimal places to be used in rounding of the waffle cells. 
#' @return returns a \link[tibble]{tibble} data frame containing the minimum and maximum extent of each \code{fill} level.
#' @author Mikko Vihtakari 
#' @keywords internal
#' @family waffle
#' @import dplyr
#' @export

waffleize <- function(dt, fill, value, composition = TRUE, max_value = NULL, digits = 3) {

   x <- dt[c(fill, value)]
   names(x) <- c("variable", "value")

  if(composition) {
    x$value <- round_preserve_sum(10^digits*x$value/sum(x$value))
  } else {

    if(is.null(max_value)) stop("max_value has to be given, if composition = FALSE")
    if(max_value < sum(x$value)) stop("max_value has to be larger than the sum of 'value' column. Use composition = TRUE, if you want a compositional waffle chart")

    x <- rbind(x, data.frame(variable = "empty", value = max_value - sum(x$value)))
    x$value <- round_preserve_sum(10^digits*x$value/max_value)
  }

  if(!is.factor(x$variable)) x$variable <- factor(x$variable, levels = c(sort(unique(x$variable)[unique(x$variable) != "empty"]), "empty"))

  x <- x[order(x$variable),]

  #tmp <- data.frame(X = 1:100, ymin = rep(c(0, (1:9)*10), each = 100), ymax = rep((1:10)*10, each = 100), variable = rep(dt[[fill]], dt[[value]]))

  tmp <- data.frame(X = 1:10^(digits-1), ymin = rep(c(0, (1:9)*10^(digits-2)), each = 10^(digits-1)), ymax = rep((1:10)*10^(digits-2), each = 10^(digits-1)), variable = rep(x$variable, x$value))

  out <- tmp %>% group_by(variable, ymin, ymax) %>% summarise(xmin = min(X)-1, xmax = max(X))

  ## Remove the empty category

  out[out$variable != "empty",]

}

#' @title Plot waffle charts
#' @description The function uses \link[ggplot2]{ggplot2} to create waffle charts from data.
#' @param data data frame to be plotted
#' @param fill character specifying the column name which should be used as fill for the waffle plot.
#' @param value character specifying the column name which contains values of the \code{fill} variable. Will be used to fill the waffle cells.
#' @param facet character specifying the column name which should be used to \code{\link[ggplot2]{facet_wrap}} waffle charts.
#' @param ncol number of columns to be used in facetting. See \code{\link[ggplot2]{facet_wrap}}.
#' @param composition logical indicating whether a compositional waffle (i.e. fill adds up to 100\%) should be created. If \code{FALSE}, waffle cells will be scaled to \code{max_value} and missing cells filled with an "empty" category.
#' @param max_value numerical giving the value to which waffle cells should be scaled to, if \code{composition = FALSE}.
#' @param digits integer indicating the number of decimal places to be used in rounding of the waffle cells. The value 3 indicates percentages, while 4 permilles. 
#' @param fill_colors named character vector giving the colors for \code{fill} levels. See \code{\link[ggplot2]{scale_fill_manual}}.
#' @param fill_title character giving the title for the color legend.
#' @param base_size numeric giving the base size for the plot. See \code{\link[ggplot2]{theme_void}}.
#' @param legend.position character specifying the position of the legend. See \code{\link[ggplot2]{ggtheme}}.
#' @details The waffle charts are read from left to right (like text) and from bottom upwards (like water glass). The cells indicate 1\% of the maximum value (100% if \code{composition = TRUE} else \code{max_value}). The cells are divided vertically to fractions specifies by the \code{digits} argument. 
#' @return Returns a \link[ggplot2]{ggplot2} waffle plot
#' @import ggplot2 dplyr
#' @family waffle
#' @author Mikko Vihtakari with code ideas from \href{https://github.com/hrbrmstr/waffle}{hrbrmstr} and \href{https://github.com/liamgilbey/ggwaffle}{Liam Gilbey}
#' @export

# data = dt; fill = "variable"; value = "value"; facet = NULL; composition = TRUE; max_value = NULL; digits = 3; fill_colors = NULL; fill_title = NULL; ncol = NULL; base_size = 12; legend.position = "bottom"
waffle_chart <- function(data, fill, value = "value", facet = NULL, composition = TRUE, max_value = NULL, digits = 3, fill_colors = NULL, fill_title = NULL, ncol = NULL, base_size = 12, legend.position = "bottom") {

  ## White 1% grid

  grid_data <- data.frame(xmin = c(0,(1:9)*10^(digits-2)), xmax = (1:10)*10^(digits-2), ymin = rep(c(0,(1:9)*10^(digits-2)), each = 10^(digits-2)), ymax = rep((1:10)*10^(digits-2), each = 10^(digits-2)))

  if(is.null(facet)) { ## No facetting

    if(any(duplicated(data[[fill]]))) stop("data contains duplicated entries in fill column. Use the facet argument or summarize data before plotting.")

    waffle_data <- waffleize(dt = data, fill = fill, value = value, composition = composition, max_value = max_value, digits = digits)

    ## Plot ####
    p <- ggplot() + 
      geom_rect(data = waffle_data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = variable)) + 
      geom_rect(data = grid_data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = NA, color = "white") +
      coord_equal(expand = FALSE) + 
      theme_void()

    ## ####

  } else { ## Facetting

    waffle_data <- data %>% group_by_(facet) %>% do(waffleize(dt = ., fill = fill, value = value, composition = composition, max_value = max_value, digits = digits))

    ## Plot ####
    p <- ggplot() + 
      geom_rect(data = waffle_data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = variable)) + 
      geom_rect(data = grid_data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = NA, color = "white") +
      facet_wrap(facet, ncol = ncol) + 
      coord_equal(expand = FALSE) + 
      theme_void()

    ## ####

  }


  ## Fill colors ####

  if(is.null(fill_title)) fill_title <- "Variable"

  if(!is.null(fill_colors)) {
    p <- p + scale_fill_manual(name = fill_title, values = fill_colors)
  } else {
    p <- p + scale_fill_viridis_d(name = fill_title)
  }

  ## Final theme manipulation

  p <- p + theme(
    legend.position = legend.position,
      aspect.ratio = 1, 
      panel.border = element_rect(color = "black", size = LS(1), fill = NA),
      strip.background = element_rect(fill = alpha("white", 0.4), color = NA),
      strip.text.x = element_text(size = base_size*0.8, margin = margin(t = 2, r = 0, b = 3, l = 0, unit = "pt")),
      plot.title = element_text(size = base_size, hjust = 0.5, face = 2),
      legend.background = element_blank(),
      legend.box.background = element_blank(),
      legend.title = element_text(size = base_size),
      legend.text = element_text(size = base_size),
      plot.background = element_blank(),
      panel.spacing = unit(0.2, units = "line"),
      legend.box.margin = margin(t = 0, r = 0, b = 3, l = 0, unit = "pt"),
      plot.margin = unit(c(0.2, 0.5, 0.1, 0.1), units = "line")
  )

  ## Return the plot

  p

}

最后,我们可以制作图表:

# Manipulate the dataset first to make sure that there are no replicate 
# entries of factors used for the waffles

data("mtcars")

mtcars$gear_vs <- paste(mtcars$gear, mtcars$vs, sep = "-")
mtcars$carb <- factor(mtcars$carb)
x <- mtcars %>% group_by(gear_vs, carb) %>% summarise(value = sum(hp))

waffle_chart(x, fill = "carb", facet = "gear_vs", value = "value")

在此输入图像描述

## You can also scale the waffles to a maximum hp in gear_vs

y <- x %>% group_by(gear_vs) %>% summarise(value = sum(value))

waffle_chart(x, fill = "carb", facet = "gear_vs", value = "value", composition = FALSE, max_value = max(y$value))

在此输入图像描述

这是另一种方法,只使用tidyverse (即dplyrtidyrggplot2 )来创建华夫 饼图方饼图 它基于hrbrmstr的答案 ,但我试图让它稍微更一般; 任何频率表都可以作为输入,很容易调整华夫饼的尺寸(例如矩形而不是方形)。

library(tidyverse)
freq_table = mtcars %>%
  count(gear, vs, carb, wt = hp) %>% 
  group_by(gear, vs) %>% 
  mutate(pct = n / sum(n)) %>% 
  select(gear, vs, carb, pct)

第二步创建坐标。 使用tidyr::expand()而不是waffleize() 还在使用smart_round()

waffle.n = 100 # Number of blocks
waffle.cols = ceiling(sqrt(waffle.n)) # For square. Otherwise pick integer.
coordinates = freq_table %>% 
  group_by(gear, vs) %>%
  mutate(waffle.num = smart_round(pct,1) * waffle.n) %>%
  group_by(carb, gear, vs) %>%
  expand(count = seq(1:waffle.num)) %>% 
  select(-count) %>%
  group_by(gear, vs) %>%
  arrange(gear, vs) %>%
  mutate(
    waffle.x = rep_len(1:waffle.cols, waffle.n),
    waffle.y = floor((row_number() - 1) / waffle.cols)
  )

我将两个变量( gearvsfacet_grid() ,因此使用facet_grid() 如果按单个变量分组,则使用facet_wrap() 您需要稍微调整选项以获得最佳结果(例如设备的大小,或点的大小和笔划)。

fig = coordinates %>%
  ggplot(aes(x = waffle.x, y = waffle.y, fill = as.factor(carb))) +
    geom_point(size = 7, shape = 22, color = "white", stroke = 0.8) +
    #geom_raster() + # Alternative to geom_point() without gap between blocks.
    facet_grid(rows = vars(gear), cols = vars(vs)) +
    theme_void() +
    theme(legend.position = "bottom", plot.margin = margin(5.5, 5.5, 5.5, 5.5, "pt"), panel.spacing = unit(15, "pt"))
fig
#ggsave("fig.pdf", width = 13, height = 17.5, units = "cm", dpi = 150)

在此输入图像描述

一个更有趣的例子 ,块数不均匀,并且共享不能被10整除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM