首页 > 解决方案 > R - 控制一组特定数据的颜色和大小

问题描述

我有一组数据,对照加4个实验。我希望强调 ggplot 中的对照组数据。我将控制组的数据放在 df_control 中,其余数据放在 df_lead 中。

这是我的代码:

    plot_lead <- ggplot() +
    geom_line(df_control, mapping = aes(CollectDate, ReportedResult, size = 0.7), show.legend = 
    TRUE) + 
    geom_point(df_control, mapping = aes(CollectDate, ReportedResult), show.legend = TRUE) +
    geom_line(df_lead, mapping = aes(CollectDate, ReportedResult, group = Site, color = Site))) +
    geom_point(df_lead, mapping = aes(CollectDate, ReportedResult, group = Site, color = Site))) +
    scale_x_date(name = "", date_breaks = "2 week", date_labels = "%Y/%m/%d") +
    scale_y_continuous(name = "Pb, mg/L") +
    theme(
    plot.title = element_text(size = 16, 
                          face = "bold",
                          family = "sans",
                          color = "black",
                          hjust = 0.5,
                          lineheight = 1.2 ), # Title
    axis.text.x = element_text(face="plain", size=10.5, angle=90), 
    axis.text.y = element_text(face="plain", size=10.5, angle=0), 
    legend.position="bottom", legend.box = "horizontal",
    panel.background = element_rect(fill='white', colour='black'), 
    panel.grid.major.y = element_line(colour = "grey")
    ) 

这是一组简短的数据:df_control:

    Site        CollectDate   Param   ReportedResult
    Control      2019-06-17    Lead    0.6 
    Control      2019-06-23    Lead    0.3
    Control      2019-07-02    Lead    1.3
    Control      2019-07-10    Lead    0.4
    Control      2019-07-17    Lead    2.3

    df_lead:
    Site        CollectDate   Param   ReportedResult
    1            2019-06-18    Lead    0.3 
    1            2019-06-22    Lead    0.2
    1            2019-07-01    Lead    1.5
    1            2019-07-10    Lead    0.9
    1            2019-07-16    Lead    3.1
    2            2019-06-17    Lead    1.3 
    2            2019-06-20    Lead    1.2
    2            2019-07-02    Lead    2.5
    2            2019-07-09    Lead    2.9
    2            2019-07-15    Lead    3.1     
    2            2019-07-22    Lead    3.3 
    3            2019-06-20    Lead    0.6
    3            2019-06-30    Lead    1.0
    3            2019-07-07    Lead    1.9
    3            2019-07-15    Lead    1.1
    3            2019-07-23    Lead    0.3 
    4            2019-06-22    Lead    0.4
    4            2019-07-01    Lead    0.5
    4            2019-07-10    Lead    0.9
    4            2019-07-16    Lead    1.1 
    4            2019-07-23    Lead    0.9 

但是,图例的名称现在显示为“大小 0.7”,并且图形看起来很丑 - 控制数据的黑色粗线。

我应该如何修改代码以便我可以控制网站的颜色并使其可区分?并且控件的图例会显示在图例中?

非常感谢!

标签: rggplot2

解决方案


我是否可以建议使用颜色来区分对照组和实验组,但前提是您像 Gregor Thomas 在评论中建议的那样加入数据。下面的代码假设连接两个数据框,键是参数,并将数据框命名为“df”

 fill_colors <- c()
 for ( i in 1:length(df$Site) ) {
   if (df$Site[i] == "Control") {
     fill_colors <- c(fill_colors, "#821122")
   } else {
     fill_colors <- c(fill_colors, "#cccccc")
   }
 }

推荐阅读