Is there any efficient way to plot ggplot using for loop? How to regular express the coloname that will be put in the ggplot function?
for example how should I regular express『satisfaction』 and『Flight.Distance』in the code?
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)
I had succeeded once using the following code:
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')
Yet, I can't replicate this experience on geom_histogram. I had tried some stupid methods but getting terrible 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)
So I try to solve this problem by removing the legend guide and add it back later on. But the legend is gone for good
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)




