双Y轴图表:一些问题

时间:2016-10-20 11:01:22

标签: r ggplot2

我想用双Y轴创建ggplot。在左侧Y轴上我想显示平均持续时间,而在右侧Y轴上显示每个工作日的平均绝对频率(即不同日期每个工作日的平均出现次数)。

        df = data.frame(c("18/10/2016","18/10/2016","14/10/2016","20/10/2016","11/10/2016"),
                        c("tuesday","tuesday","friday","thursday","tuesday"),
                        c("20","12","23","24","21"))
        colnames(df) = c("date","day","duration")

这是我到目前为止所尝试的(此代码有效,但请参阅下面的问题列表):

library("gtable")
library("grid")
library("ggplot2")

 #two plots
p1 <- ggplot(df, aes(day, duration)) + 
  geom_line(colour="#000099", position = "dodge", 
            stat = "summary", fun.y = "mean") +
  geom_point(size=3, colour="#CC0000") +
  ylab("Average duration") +
  theme_bw()

p2 <- ggplot(df) +
  geom_bar(aes(x=day), fill="#FF9999", colour="black",
           position = "dodge", stat = "summary", fun.y = "mean") + 
  ylab("Absolute frequency") +
  theme_bw()

# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(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)
## DO NOT UNDERSTAND THIS LINE
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)

此代码存在以下问题:

1)我只能看到酒吧(p2),但我看不到p1 - 带红点的蓝线。

2)右Y轴(p2)的标签未出现

3)最重要的是:看起来p2计算工作日的总出现次数,例如4个星期二。但是我想按日期对它们进行分组。例如,周二有2次出现,2016年10月18日,并且有一次出现在星期二,2016年10月11日。所以,ON AVERAGE(2 + 1)/ 2 =&gt; 1.5。

0 个答案:

没有答案
相关问题