r confidence interval plot by groups

时间:2015-12-10 01:47:11

标签: r ggplot2 confidence-interval

The dataset I am dealing with is below

testdf = structure(list(Average_Value = c(0.437, 0.8323, 0.7782, 1.4704, 
1.2134, 1.482, 0.5494, 0.7472, 0.5655, 1.053, 1.2559, 1.2933, 
1.0166, 0.4143, 0.3204, 1.0125, 0.8853, 0.9355, 1.3853, 1.4809, 
0.4797, 0.2955, 0, 0.9028, 2.6714, 1.5074, 2.5833, 0), age_gp = c("10_29", 
"30_39", "40_49", "50_59", "60_69", "70_79", "80_abv", "10_29", 
"30_39", "40_49", "50_59", "60_69", "70_79", "80_abv", "10_29", 
"30_39", "40_49", "50_59", "60_69", "70_79", "80_abv", "10_29", 
"30_39", "40_49", "50_59", "60_69", "70_79", "80_abv"), CI_UL = c("0.4602", 
"0.8652", "0.8094", "1.501", "1.243", "1.5168", "0.5763", "0.8332", 
"0.6242", "1.122", "1.3183", "1.3531", "1.0806", "0.4696", "0.3633", 
"1.0805", "0.941", "0.9831", "1.4372", "1.533", "0.5211", "0.3426", 
"0.0299", "0.9822", "2.7762", "1.6294", "2.6853", "0.0298"), 
    CI_LL = c("0.4139", "0.7993", "0.7469", "1.4397", "1.1838", 
    "1.4471", "0.5225", "0.6612", "0.5068", "0.9839", "1.1935", 
    "1.2336", "0.9525", "0.359", "0.2775", "0.9445", "0.8296", 
    "0.8879", "1.3334", "1.4288", "0.4384", "0.2483", "-0.0299", 
    "0.8233", "2.5667", "1.3854", "2.4814", "-0.0298"), BMI_GP = c(2, 
    2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 
    3, 1, 1, 1, 1, 1, 1, 1)), .Names = c("Average_Value", "age_gp", 
"CI_UL", "CI_LL", "BMI_GP"), row.names = c(NA, -28L), class = "data.frame")

I am trying to create a CI (Confidence Interval) plot for every age group

  age group: level= 7 : {"10_29", "30_39", "40_49", "50_59", "60_69", "70_79", "80_abv" }

Grouped by BMI

  BMI : level = 4 {1,2,3,4}

The final plot should look similar to this plot below

enter image description here

I can do this one at a time, meaning one plot for every BMI group, like this below, but not all the four groups together

F_BMI_RR <- testdf  # this is a guess but it gets it to work

F_BMI_RR_bmi1 = F_BMI_RR[ F_BMI_RR$BMI_GP == 1, ]

theme2 = theme(panel.background = element_rect(fill = 'white'), 
               panel.grid.minor = element_blank(), 
               text = element_text(size=20))

ggplot(F_BMI_RR_bmi1, aes(x=age_gp, y=Average_Value,colour=Average_Value)) + 
  geom_errorbar(aes(ymin=CI_LL, ymax=CI_UL, group=age_gp), width=.1) +
  geom_line(aes(group=age_gp)) +
  geom_point()+
  geom_text(aes(label=Average_Value),hjust=1.25, vjust=0)+
  theme2 +
  scale_colour_gradientn(colours=c('blue', 'red'))

Any help on producing such a plot in r is much appreciated.

1 个答案:

答案 0 :(得分:1)

library(ggplot2)
ggplot(testdf, aes(x = BMI_GP, y = Average_Value, colour = age_gp)) + geom_errorbar(aes(ymax = CI_UL, ymin = CI_LL), position = "dodge") + geom_point(position = position_dodge(0.9))