gpt4 book ai didi

r - 如何使用for循环绘制ggplot?

转载 作者:行者123 更新时间:2023-12-04 07:41:46 24 4
gpt4 key购买 nike

有什么有效的方法可以使用 for 循环绘制 ggplot 吗?如何正则表示将放入ggplot函数中的冒号?
例如我应该如何在代码中经常表达『satisfaction』和『Flight.Distance』?

ggplot(data = t1, aes(x = Flight.Distance))+
geom_histogram(aes(y = ..density.., color =satisfaction, fill =satisfaction), alpha = 0.4, position = "identity") +
geom_density(aes(color = satisfaction), size =1)
enter image description here
我曾经使用以下代码成功过一次:
plot_data_column_2 = function (data, column1, column2) {
ggplot(data, aes_string(x = column1, fill = column2)) +
geom_bar(position = position_dodge())+
guides(fill=guide_legend(title=sprintf('%s', column2)))+
xlab(sprintf('%s', column2))
}

plot_data_column_2(data = data1, column1 = 'clus_res', column2 = 'Gender')

enter image description here
然而,我无法在 geom_histogram 上复制这种体验。我曾尝试过一些愚蠢的方法,但得到的输出却很糟糕
ggplot(data = t1, aes(x = Flight.Distance))+
geom_histogram(aes(y = ..density.., color =t1[['satisfaction']] ,fill =t1[['satisfaction']]), alpha = 0.4, position = "identity") +
guides(fill=guide_legend(title='satisfaction'))+
geom_density(aes(color = t1[['satisfaction']]), size =1)

enter image description here
因此,我尝试通过删除图例指南并稍后重新添加来解决此问题。但传奇已经一去不复返了
ggplot(data = t1, aes(x = t1[['Flight.Distance']]))+
xlab('Flight.Distance')+
geom_histogram(aes(y = ..density.., color =t1[['satisfaction']] ,fill =t1[['satisfaction']]), alpha = 0.4, position = "identity") +
theme(legend.position="none")+
guides(col = guide_legend(ncol = 23))+
geom_density(aes(color = t1[['satisfaction']]), size =1)
enter image description here

最佳答案

虽然可以使用 aes_string,但它是 "soft deprecated"一个更理想化的 tidyverse 方法是使用 "curly curly" {{ }} operator from tidyeval :

my_plot <- function(df, x_var, group_var) {
df %>%
ggplot(aes(x = {{x_var}},
color = {{group_var}},
fill = {{group_var}},
group = {{group_var}})) +
geom_histogram(aes(y = ..density..),
alpha = 0.4, position = "identity") +
geom_density(size = 1, fill = NA)
}

my_plot(mtcars, mpg, factor(am))
enter image description here

关于r - 如何使用for循环绘制ggplot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67422747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com