Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding connection lines in ggplot geom_point by order of appearance

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 into a plot that takes a point for for the shares and these dots should be connected by a line.

I tried the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 very 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.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading