I am trying to combine in one graph two variables, one as a geom_pointrange [cause I need min and max representation (confidence interval 2.5% and 97.5% and its median (50%)]
other variable is a geom_point, made by median of other calculus.
I found ggplot make these representations, but I have not gotten it together, by:
#inputs
x <- seq(1:10)
n <- length(x)
yone <- 2 * runif(n)
ytwo <- runif(n)
ythree <- ytwo * 0.2
yfour <- ytwo * 2
df <- data.frame(x, yone, ytwo, ythree, yfour); df
library (ggplot2)
#yone and ytwo must be points
#ythree and yfour are min and max confidence interval (vertical line)
ggplot(df, aes(x, y = value, color = variable)) +
geom_pointrange(aes(ymin = ythree, ymax = yfour)) +
geom_point(aes(y = yone, col = "yone")) +
geom_point(aes(y = ytwo, col = "ytwo")) +
geom_line(aes(y = yfour))
Could anyone help me please?
Here is one possible solution to get the type of plot you seem to be aiming for. I've used the reshape2
package to change your data into long form. There are many options for reshaping, including tidyr
(gather), base R (reshape), and data.table
(melt). For the yone
rows in the melted data.frame, I've set the confidence intervals to NA
since you didn't compute those. Finally, I've used geom_linerange
together with geom_point
instead of geom_pointrange
, in order to handle the NA
values gracefully.
library(ggplot2)
library(reshape2)
# Reshape data to long form.
mdat <- melt(df, id.vars=c("x", "ythree", "yfour"))
# Set confidence intervals to NA for yone values,
# values for which you didn't compute CIs.
mdat[mdat$variable == "yone", c("ythree", "yfour")] <- NA
p = ggplot(data=mdat, aes(x=x, y=value, colour=variable, ymin=ythree, ymax=yfour)) +
geom_linerange() +
geom_point(size=3) +
geom_line(aes(y=yfour), linetype="dotted")
ggsave ("plot.png", p, height=4, width=6, dpi=150)