为ggplot + dplyr编写函数

nnsrf1az  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(98)

我有我的df如下。

library(dplyr)
library(ggplot2)
library(tibble)

df <- tribble(
      ~variables, ~cities, ~values,
      'var1', "C1", 2.5,
      'var1', "C2", 3.5,
      'var1', "C3", 4.9,
      'var2', "C1", 8.5,
      'var2', "C2", 7.3,
      'var2', "C3", 6.1,
      'var3', "C1", 3.1,
      'var3', "C2", 5.2,
      'var3', "C3", 7.8,   
    )

我可以使用ggplot和dplyr生成一个棒棒糖图,如下所示:

df %>% 
  filter(cities == "C2") %>%
  ggplot(aes(x = variables, y = values)) +
  geom_segment(aes(x=variables, xend=variables, y=0, yend=values), color="skyblue") +
  geom_point( color="blue", size=4, alpha=0.6) +
  coord_flip()

但是我想把这个语法写成一个函数,把城市名称作为它的输入。

tpgth1q7

tpgth1q71#

除非我遗漏了什么,否则您可以简单地将代码 Package 在函数中:

lolly <- function(city_name){
  df %>% 
    filter(cities == city_name) %>%
    ggplot(aes(x = variables, y = values)) +
    geom_segment(aes(x=variables, xend=variables, y=0, yend=values), color="skyblue") +
    geom_point( color="blue", size=4, alpha=0.6) +
    coord_flip()
}

lolly("C1")

或者看到所有三个:

cowplot::plot_grid(
  lolly("C1"),
  lolly("C2"),
  lolly("C3"),
  nrow = 3,
  labels = paste0("City = C",1:3))

相关问题