Reputation: 33
I am trying to figure out how to create this complex ggplot using the dataset below:
type | a | b | d | points | end | start |
---|---|---|---|---|---|---|
A | -0.32 | -0.02 | 0 | 1.08 | 1.14 | 1.03 |
A | -0.32 | -0.02 | 2 | 0.39 | 0.45 | 0.32 |
A | -0.32 | -0.02 | 4 | 0.25 | 0.32 | 0.17 |
A | -0.32 | -0.02 | 6 | 0.06 | 0.07 | 0.04 |
B | -0.19 | -0.02 | 0 | 1.07 | 1.12 | 1.01 |
B | -0.19 | -0.02 | 2 | 0.55 | 0.58 | 0.52 |
B | -0.19 | -0.02 | 4 | 0.43 | 0.48 | 0.39 |
B | -0.19 | -0.02 | 6 | 0.17 | 0.20 | 0.15 |
The plot will be like this:
For each "type", there will be a curve, a set of 4 points, and a set of 4 segments.
geom_function(fun = function(x) exp(a*x + b*x^2))
geom_point(aes(x = d, y = points))
geom_segment(aes(x = d, y = start, xend = d, yend = end))
scale_y_log10()
I think I know the individual details, but unfortunately I am not being able to plot it after I put everything together. The curves of the functions are not coming up, and I am getting errors. Can anyone please help?
Thank you so much!!!!
Upvotes: 1
Views: 153
Reputation: 473
Here is an alternative approach that uses geom_line()
after generating the y data:
library(dplyr)
library(ggplot2)
# replicating your data
df <- data.frame(
type = rep(c("A","B"), each = 4),
a = rep(c(-.32, -0.19), each = 4),
b = rep(-.02, 8),
d = rep(c(0:3)*2, 2),
points = c(1.08, 0.39, 0.25, 0.06, 1.07, 0.55, 0.43, 0.17),
end = c(1.14, 0.45, 0.32, 0.07, 1.12, 0.58, 0.48, 0.20),
start = c(1.03, 0.32, 0.17, 0.04, 1.01, 0.52, 0.39, 0.15))
# new data.frame for plotting the lines
n_seq <- 100 # how many y-values to generate
df_sim <- data.frame(d = rep(with(df, seq(min(d), max(d), length.out = n_seq)), 2),
type = rep(c("A", "B"), each = n_seq),
a = rep(c(-.32, -0.19), each = n_seq),
b = rep(-.02, n_seq*2)) %>%
mutate(y_hat = exp(a*d + b*d^2))
ggplot(data = df, aes(x = d, y = points, color = type)) +
geom_pointrange(aes(ymin = end, ymax = start)) + # error bar & points in one step
geom_line(data = df_sim, aes(y = y_hat, x = d, color = type)) + # instead of geom_function
scale_y_log10() +
ylab("y") # so that y-axis is labeled like the ex
Upvotes: 1