data=data.frame("X"=c(22,5,8,17,7,22),
"XMIN"=c(17.6,4,6.4,13.6,5.6,17.6),
"XMAX"=c(26.4,6,9.6,20.4,8.4,26.4),
"VAR"=c('A','B','C','A','B','C'),
"L1"=c(1,2,3,1,2,3),
"L2"=c(1,1,1,2,2,2))
ggplot(data) +
geom_pointrange(aes(
ymin = XMIN,
ymax = XMAX,
y = X,
x = reorder(VAR, -X),
colour = factor(L1),
shape = factor(L1),
linetype = factor(L2)))
I wish to add space between the lines for each variable A,B,C. Also within (A,B,C) for each variable I wish to sort the line from lowest to highest by X value.
See photo here, enter image description here
This seems to do the trick: Updated in response to comments so that variables L1
and L2
control the colour, shape and linetype aesthetics.
The really tricky problem was overcoming the conflict between the order imposed by using factor(L2)
and that wished for as a combination of VAR
and X
.
The axis order will trump the linetype order where the x values are distinct.
So created a continuous variable x_loc to locate observations on the x axis which are then re-labelled with the required values from VAR
.
library(ggplot2)
library(dplyr)
data=data.frame("X"=c(22,5,8,17,7,22),
"XMIN"=c(17.6,4,6.4,13.6,5.6,17.6),
"XMAX"=c(26.4,6,9.6,20.4,8.4,26.4),
"VAR"=c('A','B','C','A','B','C'),
"L1"=c(1,2,3,1,2,3),
"L2"=c(1,1,1,2,2,2))
# reorder the data to be in the right plotting order: grouping by VAR with X in ascending order, then everything follows quite nicely.
data1 <-
data %>%
arrange(VAR, X) %>%
mutate(x_loc = c(0.8, 1.1) + rep(0:2, each = 2))
data1
ggplot(data1) +
labs(x = "VAR") +
scale_x_continuous(breaks = 1:3, labels = data1$VAR[1:3])+
theme_minimal()+
theme(legend.position = "top")+
geom_pointrange(aes(
ymin = XMIN,
ymax = XMAX,
y = X,
x = x_loc,
linetype = factor(L2),
colour = factor(L1),
shape = factor(L1)))
Which results in:
Note: for some reason I do not fully understand adding additional ggplot
layers after the geom_pointrange
function resulted in revealing the list elements of the 'ggplot' layer. Something to follow up another time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.