【问题标题】:ggplot: Is there a way to add a color coded bar annotation to the right of the y-axis?ggplot:有没有办法在 y 轴的右侧添加颜色编码的条形注释?
【发布时间】:2021-07-15 23:14:02
【问题描述】:

假设我有这样的情节,

library(ggplot2)

p <- ggplot(iris, aes(x=Species, y=Petal.Length)) + 
  geom_violin()
p

我想要的是用一个颜色编码的条来注释右边。这可能吗?我包括了一个我画的假设情节。

【问题讨论】:

  • 你能在aes 中添加fill = Species p &lt;- ggplot(iris, aes(x=Species, y=Petal.Length, fill = Species)) + geom_violin()
  • @akrun 否,因为注释将独立于物种,否则肯定会起作用。因此,例如,我需要 3-6 为棕色,这将覆盖右侧的两个物种。
  • 一种选择是使用patchwork。参见例如我的回答here。

标签: r ggplot2


【解决方案1】:

注释功能可以完全按照您的指示进行。需要记住的是,离散尺度下面有一个连续尺度,离散类别的位置是match(x, sort(unique(x)),因此对于 iris 数据集,bar 应该从 3.5 左右开始。

library(ggplot2)

ggplot(iris, aes(Species, y = Petal.Length)) +
  geom_violin() +
  annotate(
    xmin = 3.5, xmax = 3.75,
    ymin = c(-Inf, 3, 6),
    ymax = c(3, 6, Inf),
    geom = "rect",
    fill = c("dodgerblue", "tan", "red")
  )

由reprex package (v1.0.0) 于 2021-07-16 创建

【讨论】:

  • 谢谢你这是完美的!我也意识到这也可以用来增加块注释的数量,而不是像上面的例子那样限制为三个。 ymin = c(-Inf, 3, 6, 8), ymax = c(3, 6, 8, Inf)
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 2021-10-30
  • 2020-03-20
  • 2013-07-11
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多