这是我已经问过here的问题的后续问题。我这次使用数字x轴并且无法将条形点的中点与点对齐,同时仍然允许我使用geom_line()
来连接点(见下文)。
数据
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")
剧情
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)
我尝试将d1$year
更改为一个因子,然后将点对齐到条形的中点,但是当x标度不再连续时,它不允许显示该行。
关于我如何解决这个问题的任何想法?