How to plot ggplot using for loop?

Viewed 76

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)

enter image description here 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')

enter image description here

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)

enter image description here

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)

enter image description here

2 Answers

While using aes_string is possible, it is "soft deprecated" and a more ideomatic tidyverse approach is to use the "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

Problem solved ! Sorry, I found that I forgot to add an important function which is 'aes_string', after adding it my code worked again.

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)

enter image description here

Related