代码之家  ›  专栏  ›  技术社区  ›  Delopera

R: 如何根据值填充方框图

  •  0
  • Delopera  · 技术社区  · 3 年前

    我有点小问题。我想对方框图的颜色进行适当的排序。值越低,颜色越冷,温度越高。在我的例子中有错误的排序。

    有什么办法吗?

    library(ggplot2)
    
    #  data
    set.seed(123)  
    data <- data.frame(tavg = sample(-30:30, 2000, replace = TRUE),
                       attendance = sample(100:30000, 1000, replace = TRUE))
    
    
    my_colors <- viridisLite::viridis(length(unique(cut(data$tavg, seq(-20, 30, 5)))))
    
    
    ggplot(data, aes(x = cut(tavg, seq(-20, 30, 5)), 
                     y = attendance, 
                     fill = factor(cut(tavg, seq(-20, 30, 5)), 
                     levels = unique(cut(tavg, seq(-20, 30, 5))))))+
             geom_boxplot(outlier.shape = NA) +
             geom_jitter(color = "black", size = 0.4, alpha = 0.1) +
             scale_fill_manual(values = my_colors) +
             labs(x = "Temperature", y = "Attendance", fill="Sequence") +
             ggtitle("Title") +
             theme_minimal()
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   stefan    3 年前

    问题是使用不必要的 factor(cut(tavg, seq(-20, 30, 5)), levels = unique(cut(tavg, seq(-20, 30, 5)) 你把秩序搞砸了 factor 返回者 cut 。总的来说,我建议在您的数据中添加一次带有binned值的列,然后将其映射到 x fill 以下为:

    library(ggplot2)
    
    #  data
    set.seed(123)
    
    data <- data.frame(
      tavg = sample(-30:30, 2000, replace = TRUE),
      attendance = sample(100:30000, 1000, replace = TRUE)
    )
    
    data$tavg_binned <- cut(data$tavg, seq(-30, 30, 5), include.lowest = TRUE)
    
    my_colors <- viridisLite::viridis(length(levels(data$tavg_binned)))
    
    ggplot(data, aes(
      x = tavg_binned,
      y = attendance,
      fill = tavg_binned
    )) +
      geom_boxplot(outlier.shape = NA) +
      geom_jitter(color = "black", size = 0.4, alpha = 0.1) +
      scale_fill_manual(values = my_colors) +
      labs(x = "Temperature", y = "Attendance", fill = "Sequence") +
      ggtitle("Title") +
      theme_minimal()