【问题标题】:How to plot ggplot using for loop?如何使用 for 循环绘制 ggplot?
【发布时间】:2021-05-07 01:29:27
【问题描述】:

有没有使用 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)

我使用以下代码成功了一次:

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 上复制这种体验。我尝试了一些愚蠢的方法,但得到的输出很糟糕

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)

【问题讨论】:

  • 顺便说一句,最好按总飞行时间或距离对距离进行分层以获得更清晰的视觉表示。这将减少条形图,而不会降低消息的清晰度。

标签: r ggplot2


【解决方案1】:

虽然使用 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))

【讨论】:

    【解决方案2】:

    问题解决了! 对不起,我发现我忘了添加一个重要的函数'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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      相关资源
      最近更新 更多