Search code examples
rgraphvisualizationscatter-plot

In R, how do I make flat slope graph/scatter graph with multiple values per row?


I am trying to make a chart that looks like this:

enter image description here

Except instead of the different media organisations on each row, you would have each individual survey participant (there are 47, I know this is could make for a messy chart), and then instead of "All", "Conservative" and "Labour" as the three data points on each row, it would be Survey1$Variable_X and Survey2$Variable_X. This would let me visualise the change and the magnitude of the change in this variable. Something that looks like this:

enter image description here

I did make this in a simple scatter graph just using the result of (Survey2$Variable_X - Survey1$Variable_X) but this just looks a bit boring, whereas the chart pictured above, to me, is far more interesting.

I know this is a version of a scatter chart, but does anyone have insight into how to make something like this in R, or can anyone tell me the specific name of this type of graph? I tried a slope graph but it was extremely messy:

enter image description here

Thank you in advance for any and all help :)

EDIT: Sorry, forgot to add some sample data, something like this:

  participantNum survey1_score survey2_score
1              1           -28             4
2              2           -14            16
3              3            20           -10
4              4             6             8
5              5           -20            26
6              6            22            24

Solution

  • library(tidyverse)
    
    df <- data.frame( participantNum = c(1, 2, 3, 4, 5, 6),
                      survey1_score = c(-28, -14, 20, 6, -20, 22), 
                      survey2_score = c(4,16, -10, 8, 26,24)
    )
    
    
    ggplot(df) +
      geom_segment(mapping = aes(x=factor(participantNum), xend=participantNum, y=survey1_score, yend=survey2_score), color="grey") +
      geom_point(mapping = aes(x=participantNum, y=survey1_score), color=rgb(0.2,0.7,0.1,0.5), size=3 ) +
      geom_point(mapping = aes(x=participantNum, y=survey2_score), color=rgb(0.7,0.2,0.1,0.5), size=3 ) +
      coord_flip()+
      theme(
        legend.position = "none",
      ) 
    

    sample