The code here works, you just have to change
p = ggplot(global, aes(x=as.factor(id), y=value, fill=group)) +
to
p = ggplot(data, aes(x=as.factor(id), y=value, fill=group)) +
grid_data, used in the geom_segment, is derived from data at this point.