1

我正在尝试手动将 ggplot2::geom_pointrange() 图与通过 ggplot2::geom_linerange() 实现的条形图和基于 ggplot2::geom_text() 的图例结合起来。最后,我想要一个没有任何条形图和图例标签的图。很抱歉这个很长的问题,但我看不到进一步缩短的方法。

在此处输入图像描述

这是我到目前为止尝试过的代码

library(dplyr)
library(ggplot2)

data(mpg)

# calculate average fuel consumption based on arbitrary assumption of equal
# city/highway share
mpg <- mutate(mpg, avg = (cty + hwy)/2)

# compute quantils
mpg_by_class <- group_by(mpg, class) %>%
  summarise(q10 = quantile(avg, 0.1),
            q90 = quantile(avg, 0.9),
            med = median(avg))

# compute some cross-class values
mpg_median <- median(mpg$avg)

# plotting ----
# base plot
the_plot <- ggplot() +
  geom_pointrange(data = mpg_by_class,
                  aes(x = class, ymin = q10, ymax = q90, y = med)) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

# add a bar on the right
the_plot <- the_plot +
  # build the bar
  geom_linerange(aes(x = "Y",
                     ymin = min(mpg_by_class$q10),
                     ymax = mpg_median), size = 5, colour = "green",
                 show.legend = FALSE) +
  geom_linerange(aes(x = "Y",
                     ymin = mpg_median,
                     ymax = max(mpg_by_class$q90), size = 5, colour = "red"),
                 show.legend = FALSE) +
  labs(x = "", y = "mpg") +
  # # add labels
  geom_text(aes(x = "Z", y = mean(c(min(mpg_by_class$q10), mpg_median)),
                label = "shitty"), hjust = 0) +
  geom_text(aes(x = "Z", y = mean(c(max(mpg_by_class$q90), mpg_median)),
                label = "less shitty"), hjust = 0)


print(the_plot)

“类”可能会随着数据的变化而变化,右侧彩色条中不同元素的数量也会发生变化。

我这里实际上有两个问题:

  • 彩色条位于图的最右侧的事实完全是因为我在 geom_linerange() 中输入了“Y”作为 x 美学(以及传说中的“Z”)。如果有一个空值,那么该条将被放置在其他地方,通常在最左边。没有简单的方法来组合点范围和条形图的数据,因为类和子条的数量基于手头的特定数据(我正在为 100 多个图执行此操作)。无论 x 轴上的实际类如何,有没有办法真正确保条形图位于右侧?
  • 或者,也可以将图例添加到与条形相同的“类”中,并通过使用 geom_text() 的 nudge_x 参数将图例移开一点,但我发现无法阻止 ggplot
    剪切右侧部分画布外的文本?任何解决方案仍然依赖于通过
    添加“Z”作为类别来放置在右侧的栏。可以使这个 x 轴标签
    不可见吗?
4

0 回答 0