R - ggplot dodging geom_lines

后端 未结 1 600
南笙
南笙 2020-12-18 07:20

This has been something I\'ve been experimenting with to find a fix for a while, but basically I was wondering if there is a quick way to "dodge" lineplots for two

相关标签:
1条回答
  • 2020-12-18 07:39

    You have actually two issues here:

    1. If the two lines are plotted using two layers of geom_line() (because you have two data frames), then each line "does not know" about the other. Therefore, they can not dodge each other.

    2. position_dodge() is used to dodge in horizontal direction. The standard example is a bar plot, where you place various bars next to each other (instead of on top of each other). However, you want to dodge in vertical direction.

    Issue 1 is solved by combining the data frames into one as follows:

    library(dplyr)
    df_all <- bind_rows(Group1 = df1, Group2 = df2, .id = "group")
    df_all
    ## Source: local data frame [4 x 4]
    ## 
    ##    group     id   var id_num
    ##    (chr) (fctr) (dbl)  (dbl)
    ## 1 Group1      A     1    1.0
    ## 2 Group1      A    10    1.0
    ## 3 Group2      A     1    0.9
    ## 4 Group2      A    15    0.9
    

    Note how setting .id = "Group" lets bind_rows() create a column group with the labels taken from the names that were used together with df1 and df2.

    You can then plot both lines with a single geom_line():

    library(ggplot2)
    ggplot(data = df_all, aes(x=var, y=id, colour = group))  +
       geom_line(position = position_dodge(width = 0.5)) +
       scale_color_manual("",values=c("salmon","skyblue2"))
    

    I also used position_dodge() to show you issue 2 explicitly. If you look closely, you can see the red line stick out a little on the left side. This is the consequence of the two lines dodging each other (not very successfully) in vertical direction.

    You can solve issue 2 by exchanging x and y coordinates. In that situation, dodging horizontally is the right thing to do:

    ggplot(data = df_all, aes(y=var, x=id, colour = group))  +
       geom_line(position = position_dodge(width = 0.5)) +
       scale_color_manual("",values=c("salmon","skyblue2"))
    

    The last step is then to use coord_flip() to get the desired plot:

    ggplot(data = df_all, aes(y=var, x=id, colour = group))  +
       geom_line(position = position_dodge(width = 0.5)) +
       scale_color_manual("",values=c("salmon","skyblue2")) +
       coord_flip()
    

    0 讨论(0)
提交回复
热议问题