[英]How to plot ggplot using for loop?
有没有使用 for 循环 plot ggplot 的有效方法? 如何正则表达将放在ggplot function中的冒号?
比如我应该如何在代码中正则表达『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)
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')
然而,我无法在 geom_histogram 上复制这种体验。 我尝试了一些愚蠢的方法,但变得糟糕 output
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)
因此,我尝试通过删除图例指南并稍后将其添加来解决此问题。 但传说一去不复返了
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)
虽然使用 aes_string 是可能的,但它是“不推荐使用的” ,并且更符合思想的 tidyverse 方法是使用 tidyeval 的“curly curly” {{ }} 运算符:
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))
问题解决了,抱歉,我发现我忘记添加一个重要的 function 是“aes_string”。 添加后我的代码再次工作。
ggplot(data = t1, aes_string(x = 'Flight.Distance'))+
geom_histogram(aes_string(y = '..density..', color ='satisfaction', fill ='satisfaction'), alpha = 0.4, position = "identity") +
geom_density(aes_string(color = 'satisfaction'), size =1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.