facet_gridded马赛克图上的Geom_text

时间:2011-06-27 07:56:21

标签: r ggplot2 data-visualization

我正在尝试将geom_text标签添加到下面的马赛克图中:

Mosaic Plot

我使用ggplot2生成的代码如下:

tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
          facet_grid(helmet~.) +
          geom_text(aes(x = c(9.0, 22.0, 33.0, 46.0, 72.0, 98.0),
                        y = 125,
                        label = c("C", "DS", "S", "ST", "Std", "T")),
                        size = 3) +
          scale_fill_brewer(palette = "Greys") +
          xlab("Percentage of Sample") +
          ylab("Percentage Responded") +
          opts(title="Mosaic Plot of Helmet Type Use",
               legend.position="none") +
          scale_x_continuous(expand = c(0, 0)) +
          scale_y_continuous(expand = c(0, 125)) +
          ylim(0, 101)

我有两个问题:

  • ylim在顶部切断了我的geom_text。
  • 如果没有ylim()函数,前三个类别显示在奇数面上方,最后三个类别显示在偶数面上方,从最上面的面开始计算。我无法弄清楚这是怎么回事。

我只想将六个类别添加到情节的顶部。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

Andrie说,用数据测试很难。但是你想在你的第一个任务中使用coord_cartesian限制,因为比例限制会抛弃超出范围的数据。这是我的解决方案,我合并了实验室和秤,因为有时它们会发生碰撞。

tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
          facet_grid(helmet~.) +
          geom_text(aes(x = c(9.0, 22.0, 33.0, 46.0, 72.0, 98.0),
                        y = 125,
                        label = c("C", "DS", "S", "ST", "Std", "T")),
                        size = 3) +
          scale_fill_brewer(palette = "Greys") +
          opts(title="Mosaic Plot of Helmet Type Use",
               legend.position="none") +
          scale_x_continuous("Percentage of Sample", expand = c(0, 0)) +
          scale_y_continuous("Percentage Responded", expand = c(0, 125)) +
          cood_cartesian(ylim = c(0, 101))

HTH

答案 1 :(得分:0)

我只需将geom_text分成两半并拥有两个函数,就得到了我想要的东西。我不知道为什么会这样,但确实如此!

tsc.p <- ggplot(tsc, 
                aes(ymin = ymin, ymax = ymax,
                    xmin = xmin, xmax = xmax,
                    fill = variable))
tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
          facet_grid(helmet~.) +
          geom_text(aes(x = c(9.0, 22.0, 33.0),
                        y = 25,
                        label = ifelse(helmet == "FF",
                                       c("Cru", "DualSp", "Sport"),
                                       "")),
                        size = 3) +
          geom_text(aes(x = c(45.0, 72.0, 97.0),
                        y = 25,
                        label = ifelse(helmet == "FF",
                                       c("SptTour", "Std", "Tour"),
                                       "")),
                        size = 3) +
          scale_fill_brewer("Frequency of Helmet Use", palette = "Greys") +
          xlab("Percentage of Sample") +
          ylab("Percentage Responded") +
          opts(title="Mosaic Plot of Helmet Use by Helmet Type") +
          scale_x_continuous(expand = c(0, 0)) +
          scale_y_continuous(expand = c(0, 101)) +
          ylim(0, 101)

图表:

Mosaic Plot