ggplot2饼图作为独立代码而不是自定义函数

时间:2018-01-19 16:02:53

标签: r ggplot2

我正在编写一个自定义函数来制作带有ggplot2的饼图。我编写的代码工作正常,但是当我使用内部函数体启动时,它会停止工作。有什么想法可能会发生这种情况吗?

dataframe <- as.data.frame(cbind(gender = c("male", "female", "female", "female", "male", "female", "male"),
                           pet = c("dog", "cat", "dog", "cat", "cat", "cat", "dog")))

library(dplyr)

## as standalone code

df <- dplyr::group_by_(dataframe, .dots = c('gender', 'pet')) %>%
  dplyr::summarize(counts = n()) %>%
  dplyr::mutate(perc = (counts / sum(counts)) * 100) %>%
  dplyr::arrange(desc(perc))

ggplot2::ggplot(df, aes('', counts)) +
  geom_col(position = 'fill', aes(fill = factor(pet))) +
  facet_wrap(~gender, labeller = "label_both") +
  geom_label(
    aes(label = paste0(round(perc), "%"), fill = factor(pet)),
    position = position_fill(vjust = 0.5),
    color = 'black',
    size = 5,
    show.legend = FALSE
  ) +
  coord_polar(theta = "y")

## as custom function

ggpiecustom <- function(data, condition, main) {

df <- dplyr::group_by_(data, .dots = c(condition, main)) %>%
  dplyr::summarize(counts = n()) %>%
  dplyr::mutate(perc = (counts / sum(counts)) * 100) %>%
  dplyr::arrange(desc(perc))

ggplot2::ggplot(df, aes('', counts)) +
  geom_col(position = 'fill', aes(fill = factor(main))) +
  facet_wrap(condition, labeller = "label_both") +
  geom_label(
    aes(label = paste0(round(perc), "%"), fill = factor(main)),
    position = position_fill(vjust = 0.5),
    color = 'black',
    size = 5,
    show.legend = FALSE
  ) +
  coord_polar(theta = "y")
}

ggpiecustom(data = dataframe, condition = 'gender', main = 'pet')

reprex package(v0.1.1.9000)于2018-01-19创建。

1 个答案:

答案 0 :(得分:2)

问题是ggplot在您的函数中,看到factor('pet')并为每个人分配pet的相同值。使用get(main)指定您希望对象具有在main中指定的名称。

dataframe <- as.data.frame(cbind(gender = c("male", "female", "female", "female", "male", "female", "male"),
                                 pet = c("dog", "cat", "dog", "cat", "cat", "cat", "dog")))


ggpiecustom <- function(data, condition, main) {

  df <- dplyr::group_by_(data, .dots = c(condition, main)) %>%
    dplyr::summarize(counts = n()) %>%
    dplyr::mutate(perc = (counts / sum(counts)) * 100) %>%
    dplyr::arrange(desc(perc))

  ggplot2::ggplot(df, aes('', counts)) +
    geom_col(position = 'fill', aes(fill = factor(get(main)))) +
    facet_wrap(condition, labeller = "label_both") +
    geom_label(
      aes(label = paste0(round(perc), "%"), fill = factor(get(main))),
      position = position_fill(vjust = 0.5),
      color = 'black',
      size = 5,
      show.legend = FALSE
    ) +
    coord_polar(theta = "y")
}

ggpiecustom(data = dataframe, condition = 'gender', main = 'pet')