首页 > 解决方案 > 仅在指定因素之间连接 geom_line

问题描述

我有一个数据集,其中包含四个不同月份的 4 个治疗组的直径值。我正在Diameter ~ Treatment为每个月以及Diameter changes between months ~ Treatment.

数据集如下所示:

# 包含每个月的直径和月份之间的直径差异的数据

> 头部(收集的直径和治疗数据)
  治疗月直径
1 Aux_Drop Diameter_mm.Sep01 55.88
2 Aux_Spray Diameter_mm.Sep01 63.50
3 DMSO 直径_mm.Sep01 66.04
4 水径_mm.Sep01 43.18
5 Aux_Drop Diameter_mm.Sep01 38.10
6 Aux_Spray Diameter_mm.Sep01 76.20


# 包含每个月平均直径和平均直径变化的数据

> 头部(子均值直径)
  治疗月直径 SEdiam
1 Aux_Drop Diameter_mm.Dec 83.63857 29.62901
2 Aux_Drop Diameter_mm.Feb01 101.20923 24.84024
3 Aux_Drop Diameter_mm.Feb02 110.00154 22.51364
4 Aux_Drop Diameter_mm.Jan 93.00308 25.13485
5 Aux_Drop Diameter_mm.Mar 116.84000 22.19171
6 Aux_Drop Diameter_mm.Nov01 74.50667 17.40454


这是我的代码:

# assign the factors name to pick
factorsOnXaxis.DiameterByMonth = c(
    "Diameter_mm.Sep01", "DiameterDiff.Sep01ToDec", "Diameter_mm.Dec", "DiameterDiff.DecToMar", "Diameter_mm.Mar")

# assign name to above factors
factorsOnXaxisName = c('Sep','Dec-Sep','Dec', 'Mar-Dec', 'Mar')    


# start plotting 
gatheredDiameterAndTreatmentData  %>%
  subset(Diameter != "NA") %>%
  ggplot(aes(x = factor(Month), y = Diameter)) + 
  geom_point(aes(colour = Treatment), na.rm = TRUE, 
             position = position_dodge(width = 0.2)) +
  geom_point(data = subMeansDiameter, size = 4, aes(colour = Treatment), 
             na.rm = TRUE, position = position_dodge(width = 0.2)) +

  theme_bw() + # remove background 

  # add custom color to the "Treatment" levels 
  scale_colour_manual( 
    values = c("Aux_Drop" = "Purple", "Aux_Spray" = "Red", 
               "DMSO" = "Orange", "Water" = "Green")) + 

  # rearrange the x-axis
  scale_x_discrete(limits = factorsOnXaxis.DiameterByMonth, labels = factorsOnXaxisName) +

  # to connect the "subMeans - Diameter" values across time points
  geom_line(data = subMeansDiameter, aes(
    x = Month, y = Diameter, group = Treatment, colour = Treatment), 
    position = position_dodge(width = 0.2)) 

这给了我这样的情节:

在此处输入图像描述

而不是geom_line每个时间点的连接线,我希望在指定的 x 轴因子之间连接线,即

  1. 九月、十二月、三月之间
  2. 12 月至 9 月至 3 月至 12 月之间


我试图操纵geom_line用作的代码行:

geom_line(data = subMeansDiameter, aes(
    x = c("DiameterDiff.Sep01ToDec", "DiameterDiff.DecToMar"), y = 直径, 组 = 治疗, 颜色 = 治疗),
    位置 = position_dodge(宽度 = 0.2))

连接到 之间的Dec-Sep线Mar-Dec

但是,这是行不通的。如何更改我的代码?

这是我存储为 *.tsv 的数据文件。

collectDiameterAndTreatmentData = http://s000.tinyupload.com/index.php?file_id=38251290073324236098

subMeans = http://s000.tinyupload.com/index.php?file_id=93947954496987393129

标签: rggplot2plot

解决方案


在这里,您需要明确定义组,因为颜色还不够。

你的例子是不可重现的,但这里有一些东西会给你这个想法,这是一个没有明确组的情节:

ggplot(iris,aes(Sepal.Width, Sepal.Length, color = Species)) + geom_line()

在此处输入图像描述

现在这里有一个具有群体审美的,我已经使用Sepal.Length's 值拆分了数据,但你很可能会使用ifelse一个月的 deending:

ggplot(iris,aes(Sepal.Width, Sepal.Length, color = Species, 
                group = interaction(Species, Sepal.Length > 5.5))) + 
  geom_line()

在此处输入图像描述


推荐阅读