将数据帧变量传递给 ggplot2 函数

问题描述 投票:0回答:1

问题:

  • 无法解析传递给 ggplot2 中的 df 变量
    scale_y_continous

目标:

  • 动态执行具有比例的辅助轴。

我的解决方法目前是手动写入总和,这不是最好的方法,或者将 df 保存在变量中并使用

df$count

访问它

询问:

  • 如何动态访问 df 变量
    .$count

可重现示例:

mtcars %>% 
  group_by(gear) %>% 
  summarise(count = n()) %>% 
  {
  ggplot(data = . , aes(x = gear, y = count)) +
  geom_col() +
  coord_flip() +
  
  scale_y_continuous(labels = comma_format(),
                     sec.axis = sec_axis(~./32, #sum(.$count), 
                                         labels = scales::percent,
                                         name = "proportion")
                     ) 
  }
  

参考: 如何访问已传递给 ggplot() 的数据框?

r ggplot2 dplyr
1个回答
1
投票

您正在向

transform
 提供 
sec_axis()
参数,其定义为:

严格单调变换的公式或函数

您正在使用公式符号来使用

.
来引用所需的列,并且您可以继续使用它除以
sum(.)
来计算比例。

顺便说一句,在绘图之前也不需要

group_by()
summarise()
,因为您可以只使用
geom_bar()
,默认情况下为
stat = "count"
。这可以避免管道连接到大括号。

ggplot(mtcars, aes(x = gear)) +
    geom_bar() +
    coord_flip() +
    scale_y_continuous(
        labels = comma_format(),
        sec.axis = sec_axis(
            ~ . / sum(.),
            labels = scales::percent,
            name = "proportion"
        )
    )

如果您更喜欢使用匿名函数来表示公式,可以将

~ . / sum(.)
替换为
\(x) x / sum(x)

© www.soinside.com 2019 - 2024. All rights reserved.