简体   繁体   中英

How to plot ggplot using for loop?

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)

在此处输入图像描述

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))

在此处输入图像描述

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM