I was wondering how to connect vertical lines from individual subject data points to a horizontal line. My main issue is that the x-axis is grouped and does not have a continuous variable to specify the position of the line. If I make the line come down from the group (xend), I just end up with 1 vertical line for each group.
Here is what I currently have
ggplot() +
geom_point(data = df, aes(x = Group, y = Number, color = Group), position = "jitter") +
geom_hline(yintercept = 33.25)
If I add
geom_segment(data = df,
aes(x=Group,
xend=Group,
y=Number,
yend=33.25))
I end up with the one vertical line per group, rather than stemming from each subject
To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.
The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)
A scatter plot can be created using the function plot(x, y). The function lm() will be used to fit linear models between y and x. A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().
How to add reference lines to a Bar Plot in R - How To in R. Horizontal reference lines can be added to a Box Plot using the abline function. Vertical reference lines cannot be added to box plots. The default reference line is a simple black line.
Good news is that the upcoming version of ggplot2 provides reproducible jitter. Bad news is that geom_segment()
doesn't allow jitter, so use geom_linerange()
instead.
We will be able to specify seed
like bellow. Hope the version will be released soon! In the meantime, you should manually add jitter to the data as answered on https://stackoverflow.com/a/21922792/5397672.
reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-12
library(ggplot2)
set.seed(2)
dat <- iris[sample(1:nrow(iris), 20),]
ggplot(dat, aes(x=Species, y=Petal.Width)) +
geom_point(position = position_jitter(height = 0L, seed = 1L)) +
geom_hline(yintercept=0.75) +
geom_linerange(aes(x=Species, ymax=Petal.Width, ymin=0.75),
position = position_jitter(height = 0L, seed = 1L))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With