0

This is a follow on question from one I have already asked here. I using a numeric x axis this time and am having trouble aligning the midpoint of the bars with the points while still allowing me to use geom_line() to connect the points (seen below).enter image description here

Data

d1<-structure(list(year = c(2004, 2005, 2006, 2007, 2008, 2009, 2010, 
2011, 2012, 2013), amount = c(45108739.14, 48015147.4849, 62445243.4101, 
77714328.16, 77807411.64, 81008163.47, 78724707.02, 82632065.1736, 
79801921.81, 89934798.65), gifts = c(13223L, 16022L, 18570L, 
21577L, 21756L, 22528L, 22879L, 25031L, 25544L, 28554L)), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"), .Names = c("year", 
"amount", "gifts"), sorted = "year")

Plot

p1 <- ggplot(d1, aes(x=year,y=amount)) +
  geom_bar(stat="identity", fill="orange") +
  scale_y_continuous(labels=dollar, expand=c(0,0))

p2 <- ggplot(d1, aes(x=year, y=gifts)) +
  geom_point(size=6,colour="grey50") +
  geom_line(colour="grey50", size=1) +
  scale_y_continuous(labels=comma, expand=c(0,0))+
  expand_limits(y=0) +
  theme(panel.background = element_rect(fill = NA),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))


pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,
                     pp$l, pp$b, pp$l)
# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
# add legend
leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]

g$grobs[[which(g$layout$name == "guide-box")]] <-
  gtable:::cbind_gtable(leg1, leg2, "first")

# draw it
grid.draw(g)

I tried changing d1$year to a factor and it aligned the points to the midpoint of the bars, however as the x-scale is no longer continuous it doesn't allow show the line.

Any ideas on how I can resolve this?

Community
  • 1
  • 1
Dan
  • 2,625
  • 5
  • 27
  • 42
  • Have you tried playing with position=position_dodge(.9) in geom_point? This might help move the position of the points. – Docconcoct Nov 06 '14 at 06:20
  • I had a try with that, however while it aligns the first point, all the others are shifted to the right of the centre. It looks like something needs to be adjusted with a left and right margin, however I am not sure if this is possible. – Dan Nov 06 '14 at 06:32
  • 3
    Your solution with `year` as factor will work if you will add `group=1` to `aes()` of `p2` plot. – Didzis Elferts Nov 06 '14 at 06:35
  • Group=1 did the trick. – Dan Nov 08 '14 at 20:16

0 Answers0