ggplot:从同一点开始的多条线

3
我有一个类似这样的数据集:
df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
                       "Sp A", "Other sp", "Other sp"), 
           Study = c("A", "A", "A", "A", 
                     "B", "B", "B"), 
           Value = c(1, 3, 4, 5, 3, 6, 7))

Looks like this :

> df
   Species Study Value
1     Sp A     A     1
2 Other sp     A     3
3 Other sp     A     4
4 Other sp     A     5
5     Sp A     B     3
6 Other sp     B     6
7 Other sp     B     7

我希望能够比较物种A的值和同一研究中其他物种的值。
这是目前我拥有的图表:
ggplot(df, aes(y = Value, x = Species)) + 
    geom_point(shape = 1) +
    geom_line(aes(group = Study), color = "gray50") +
    theme_bw()

enter image description here

我不想要竖线。相反,我想要5条线,其中3条从下面的“Sp A”点开始,朝着同一研究(A)中对应的“其他sp”点,另外2条从上面的“Sp A”开始,朝着同一研究(B)中的另外2个点。
2个回答

4

可能有更加优雅的方法,但是这里提供一个可行的解决方案。诀窍在于稍微重新排列数据,然后使用geom_segment

library(tidyverse)
df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
                             "Sp A", "Other sp", "Other sp"), 
                 Study = c("A", "A", "A", "A", 
                           "B", "B", "B"), 
                 Value = c(1, 3, 4, 5, 3, 6, 7))

# Split data
other <- df %>% filter(Species == "Other sp")
sp_a <- df %>% filter(Species == "Sp A")

# Recombine into the data set for plotting
df <- other %>%
  inner_join(sp_a, by = "Study")

# Make the plot
ggplot(df, aes(x = Species.y, y = Value.y)) +
  geom_segment(aes(xend = Species.x, yend = Value.x, colour = Study))

按需调整图表。仍需要进一步调整标签、点等内容

根据需要调整图表!


谢谢你的建议。在接受你的答案之前,我会等待看看是否有更直接的方法。顺便说一下,我认为你应该删除 slice 行。这是不必要的,并且会导致相同行的乘法。在基本 R 中使用 merge(df[df$Species == "Sp A",], df[df$Species != "Sp A",], by = "Study", all = TRUE) 可以得到相同的结果。 - Gilles San Martin
那将是一种尝试一件事,然后在回答中改变方向的情况!我现在已经更正了答案。 - jkeirstead
这是唯一的方法,除非有针对“其他sp”的唯一标识符。例如,在您的数据中无法区分“其他sp”-“Sp A”对在value=6value=7时的情况。 - Brian

2
如果你想为每个Study级别做同样的事情,可以使用geom_line。你需要复制相应数量的Sp A行来匹配Other sp行的数量,并为每对Sp AOther Sp分配一个唯一的ID作为group参数。保留HTML标签,不进行解释。
library(tidyverse)

df %>% group_by(Study) %>% 
  slice(c(rep(1,length(Species[Species=="Other sp"])),2:n())) %>%  
  group_by(Study, Species) %>% 
  mutate(ID = paste0(Study, 1:n())) %>% 
  ggplot(aes(y = Value, x=Species, group=ID, colour=Study)) + 
    geom_point(shape=1) +
    geom_line() +
    theme_bw()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接