【问题标题】:ggplot : multiple lines starting from the same pointggplot :从同一点开始的多行
【发布时间】:2017-08-03 21:54:50
【问题描述】:

我有一个像这样的数据集:

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))

看起来像这样:

> 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()

我不想要垂直线。取而代之的是,我想要 5 条线,3 条从较低的“Sp A”点开始,指向同一研究 (A) 的 3 个相应的“其他 sp”点,2 条从上部的“Sp A”开始,指向来自同一研究的其他 2 点 (B)。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    可能有一种更优雅的方式来做到这一点,但这里有一个可行的解决方案。诀窍是稍微重新排列数据,然后使用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 行。这是不必要的,并且会导致相同行的倍增。与merge(df[df$Species == "Sp A",], df[df$Species != "Sp A",], by = "Study", all = TRUE) 在基数 R 中的结果相同
    • 这将是尝试一件事然后在答案中改变方向的情况!我现在已经更正了答案。
    • 这是唯一的方法,除非“Other sp”有唯一标识符。例如,您的数据无法区分 value=6value=7 处的“Other sp”-“Sp A”对。
    【解决方案2】:

    您可以使用geom_line 执行此操作,如果对于Study 的每个级别,您复制Sp A 行数以匹配Other sp 行数,然后为每对@ 分配一个唯一ID 987654327@ 和 Other Sp 用于 group 美学。

    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()
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2016-07-04
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多