Home > Software engineering >  Adding connection lines in ggplot geom_point by order of appearance
Adding connection lines in ggplot geom_point by order of appearance

Time:04-13

I have data that looks like this:

             phase_f     share
1: Conceptualization 0.5000000
2:            Growth 0.6666667
3:              Idea 0.2777778
4:        Incubation 0.8333333

and I want to plot that data that takes a point for the shares and these dots should be connected by a line.

I tried the following code:

test <- ggplot(aes(y = phase, x = share)   
  geom_point()  
  geom_line() 
  labs(x= "% of answers", y = "") 

This gives me the following plot 1: Plot 1 where line doesn't connect adjacent categories

It works nicely, but I want the line between the dots to connect adjacent categories, that is, idea to conceptualization to incubation to growth. In the example, I want to erase the connection between Idea and incubation and instead have the line between conceptualization and incubation as manually corrected here:

Sloppy plot 3 which should be the final example

If I switch x- and y-axis, this works - each category is connected to the adjacent categories (plot 2): Plot 2 where line connects adjacent categories but x- and y-axis are switched

How do I have to adjust my code so that I keep the x- and y-axis as in plot 1 but keep the order of the connections as in plot 2?

Thanks so much in advance for your support.

CodePudding user response:

Try using geom_path instead of geom_line with group = 1.

From the documentation (?geom_line):

geom_path() connects the observations in the order in which they appear in the data. geom_line() connects them in order of the variable on the x axis

library(ggplot2)

df <- read.table(header = T, text = "phase_f     share
Conceptualization 0.5000000
Growth 0.6666667
Idea 0.2777778
Incubation 0.8333333")

ggplot(df, aes(y = phase_f, x = share, group = 1))   
         geom_point()  
         geom_path()  
         labs(x= "% of answers", y = "") 

Created on 2022-04-12 by the reprex package (v2.0.1)

  • Related