我试图将这段代码重构为一个函数,但它没有给我带来预期的输出.在原始代码中,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")