在ggplot2中,根据给定条件对齐绘制的线

问题描述 投票:0回答:0

让我们有以下虚拟数据:

library(tidyverse)
library(ggplot2)

df <- tibble(
  id = c(rep("abcdef-123", 3), rep("defghi-678", 2), rep("mnopqr-345", 1)),
  length = c(rep(137, 3), rep(293, 2), rep(91, 1)),
  position = c(10, 77, 103, 82, 222, 45)
)

这个数据框包含 3 列。 “id”对应于对象(项目)名称,“length”对应于项目的总长度,而“position”表示在给定的“length”中发生有趣特征的位置。所以每个唯一的“id”都有其唯一的“长度”,而每个“id”可能观察到不止一个“位置”。

我按“id”对数据进行分组,因为这是每个项目的唯一标签:

df_grouped <- df %>% group_by(id)

然后我想按以下方式绘制数据:

  • 每个“id”应该被描绘成一个单独的水平线
  • 位置应标记为点
  • 线条应根据每个“id”中的第一个(或理想情况下:选择的)位置对齐

这是我目前能够得到的:

ggplot2::ggplot(df_grouped, aes(x=length, y=id, xend=0, yend=id)) + 
  ggplot2::geom_segment()+ 
  ggplot2::geom_point(aes(x=position, y=id), size=2) + 
  ggplot2::theme_void() +
  ggplot2::theme(axis.ticks.x = element_blank(), axis.text.x = element_blank())#+ggplot2::scale_y_discrete()

这就是我想要实现的(我在 gimp 中制作的):

我不知道如何有条件地对齐线(根据选择的第一个或第 n 个位置)。我尝试了多种解决方案,包括在将参数传递给美学时在括号中索引位置。这没有用,所以我正在寻求帮助。

目前正在尝试用 Bioconductor 解决这个问题,但希望能使用 base R 或 ggplot2 解决方案。

r ggplot2 alignment
© www.soinside.com 2019 - 2024. All rights reserved.