我试图将这段代码重构为一个函数,但它没有给我带来预期的输出.在原始代码中,color个级别被映射到单个绘图--这是所需的行为.在重构后的代码中,我得到了一个单级为color的图.没有任何错误或任何东西,我在函数调用中使用browser()来确认级别,使用unique(),一切看起来都是正确的.不知道为什么这不管用.

工作代码示例:

#### Load and prep the data set####
data(diamonds)

### Create bins for carat ###
carat_bins <- seq(0, ceiling(max(diamonds$carat) * 2) / 2, by = 0.5)  

### Add the bins to the table ###
diamonds$carat_bin <- cut(diamonds$carat, breaks = carat_bins, include.lowest = TRUE)

#### Plot ####
ggplot(diamonds, aes(x = carat_bin, y = price, fill = color)) +
  geom_violin(position = "identity", alpha = 0.15) +
  labs(x = "Carat", y = "Price", fill = "Color") +
  ggtitle("Distribution of Diamond Prices by Carat and Color") +
  theme_minimal()

Example Refactored Code (function replaces Plot section above):

#### Plot Function ####
my_plot <- function(x_var, fill_var) {
  
  ### Ensure fill_var is factored ###
  diamonds[[fill_var]] <- factor(diamonds[[fill_var]])
  
  ggplot(diamonds, aes(x = x_var, y = price, fill = fill_var)) +
    geom_violin(position = "identity", alpha = 0.15)
}

#### Test ####
my_plot("carat_bin", "color")

工作代码输出:

plot correctly factored by color level

重构代码的输出:

plot incorrectly ignoring color levels

推荐答案

使用!!ensym()(因此ggplot将字符串计算为变量):

library(tidyverse)

data(diamonds)

### Create bins for carat ###
carat_bins <- seq(0, ceiling(max(diamonds$carat) * 2) / 2, by = 0.5)  

### Add the bins to the table ###
diamonds$carat_bin <- cut(diamonds$carat, breaks = carat_bins, include.lowest = TRUE)


#### Plot Function ####
my_plot <- function(x_var, fill_var) {
  
  ### Ensure fill_var is factored ###
  diamonds[[fill_var]] <- factor(diamonds[[fill_var]])
  
  ggplot(diamonds, aes(x = !!ensym(x_var), y = price, fill = !!ensym(fill_var))) +
    geom_violin(position = "identity", alpha = 0.15)
}

#### Test ####
my_plot("carat_bin", "color")

创建于2024-03-16年第reprex v2.1.0

R相关问答推荐

在通过最大似然估计将ODE模型与数据匹配时,为什么要匹配实际参数的转换值?

在(g)子中使用asserable字符

使用gggrassure减少地块之间的空间

在"gt"表中添加第二个"groupname_col",而不连接列值

错误:非常长的R行中出现意外符号

在ggplot中为不同几何体使用不同的 colored颜色 比例

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

根据现有列的名称和字符串的存在进行变异以创建多个新列

识别连接的子网(R-igraph)

如何使用同比折线图中的个别日

为什么在写入CSV文件时Purrr::Pwalk不起作用

如何在使用Alpha时让geom_curve在箭头中显示恒定透明度

以任意顺序提取具有多个可能匹配项的组匹配项

在ggploy中创建GeV分布时出错

计算多变量的加权和

R/shiny APP:如何充分利用窗口?

如何捕获这个shiny 的、可扩展的react 性用户输入矩阵作为另一个react 性对象,以便进一步操作?

Ggplot2:添加更多特定 colored颜色 的线条

使用相对风险回归计算RR

如何将数据框压缩为更宽,同时将行输入保持为行输入,而不是R中的列名?