To link discrete variables together, we use group=1
as recommended here
Now the aim is to link the red dots using a line, and the same applies for the blue dots.
If I use the following code:
ggplot(df, aes(x = cohort, y = est,color=name,group=1))
geom_point(position=position_dodge(width=0.3))
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0,position=position_dodge(width=0.3))
geom_line(position=position_dodge(width=0.3))
I get this:
Here is my data:
df=structure(list(est = c(-0.0584741125344448, 0.021444947354496,
0.0283447339408831, 0.040105980055471, 0.0374816335738256, -0.00876274041718853
), se = c(0.0139423923119975, 0.0116604369679277, 0.012226641006313,
0.0224145123205577, 0.0207370700447159, 0.0214173453687987),
cohort = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("S",
"B", "G"), class = "factor"), upper = c(-0.0332526819060428,
0.0416835581439528, 0.0495098759734735, 0.0840384242037641,
0.0781262908614688, 0.0332152565056569), lower = c(-0.0836955431628468,
0.00120633656503907, 0.00717959190829267, -0.0038264640928221,
-0.0031630237138175, -0.0507407373400339), name = structure(c(2L,
2L, 2L, 1L, 1L, 1L), .Label = c("Low-skilled working class",
"Upper-middle class"), class = "factor")), row.names = c("Silent generation...1",
"Baby boomers...2", "Generation X...3", "Silent generation...4",
"Baby boomers...5", "Generation X...6"), class = "data.frame")
CodePudding user response:
You could set group
in your line to the variable name
. I set an alpha for the error bars to make the plot more clear. You can use this code:
ggplot(df, aes(x = cohort, y = est,color=name))
geom_point(position=position_dodge(width=0.0))
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0,position=position_dodge(width=0.0), alpha =0.5)
geom_line(aes(x = cohort, y = est, group = name))
Output: