geom_bar与geom_line的问题。酒吧在合并的地块中消失了

时间:2015-08-20 02:18:07

标签: r ggplot2 geom-bar

我有一个条形图和一个线条图,想要将它们组合起来。 我找到了双轴问题的正确调整代码。 但我的酒吧里的酒吧消失了。你能救我吗?

#code to stack overflow
library(ggplot2)
library(gtable)

temp = data.frame(Product=as.factor(c("A","B","C")),
                  N = c(17100,17533,6756),
                  n = c(5,13,11),
                  rate = c(0.0003,0.0007,0.0016),
                  labels = c(".03%",".07%",".16%"))

p1 = ggplot(data = temp, aes(x=Product,y=N))+
  geom_bar(stat="identity",fill="#F8766D")+geom_text(aes(label=n,col="red",vjust=-0.5))+
  theme(legend.position="none",axis.title.y=element_blank(),axis.text.x = element_text(angle = 90, hjust = 1))

p2 = ggplot(data = temp,aes(x=Product,y=rate))+
  geom_line(aes(group=1))+geom_text(aes(label=labels,fill="black",vjust=0))+
  theme(legend.position="none",axis.title.y=element_blank(),
        axis.text.x = element_text(angle = 90, hjust = 0))+
  xlab("Product")
#code to stack overflow

#new code learned from SO

# extract gtable
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)

# overlap the panel of 2nd plot on that of 1st plot
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)

# draw it
grid.draw(g)

barplot

enter image description here

enter image description here

0 个答案:

没有答案