gpt4 book ai didi

r - ggplot : rearrange factor order and highlight area by `geom_rect` at the same time

转载 作者:行者123 更新时间:2023-12-04 02:06:32 36 4
gpt4 key购买 nike

首先,为 ggplot 指定分类变量顺序的方法是在 data.frame 中对其级别重新排序。其次,要在任何绘图上突出显示一个区域,我们可以使用 geom_rect。这里需要注意的是,不要将数据传递给geom_rect,否则不会让我们设置alpha,这样网格线就不会可见的。现在有2种情况:

  • 如果我们将数据传递给 geom_rect(或传递给顶层 ggplot()),则顺序与 data.frame ,但正如我提到的,矩形不会是透明的
  • 如果我们只将数据传递给 geom_point 层,ggplot 会按字母顺序重新排列离散变量

如何同时拥有这两个条件,即具有预定义的顺序并在所需位置具有透明矩形?

奖励问题:如何在离散变量处创建一个矩形,其边缘位于网格线之间,即按 0.5 调整? vjusthjust 不是这里使用的参数(警告告诉我们)。以及如何使矩形填充整个垂直空间(为此我们需要将 ymax 定义为第 n+1 因子级别,这不存在)。

require(ggplot2)

ex <- data.frame(a = factor(letters[1:10]),
b = factor(rep(c('b', 'a'), 5)),
c = rep(letters[1:5], 2))

ex$a <- factor(ex$a, levels = ex$a[order(ex$b)])

ggplot(
# uncomment this to see the other failure:
# ex, aes(y = a, x = c)
) +
geom_rect(
aes(
xmin = 'b',
xmax = 'd',
ymin = 'd',
ymax = 'j'
),
alpha = 0.2
) +
geom_point(
data = ex,
aes(
y = a,
x = c
)
)

最佳答案

我能做的最好的事情就是通过使用 annotate(一个数据自由层)来避免 data 问题。你不知何故需要把 geom_point 放在第一位,但我不确定为什么。比例似乎是由第一层决定的,即使我已经在 ggplot 中提供了数据和映射。

ggplot(data = ex, aes(y = a, x = c)) +
geom_point() +
annotate(xmin = 'b', xmax = 'd', ymin = -Inf, ymax = Inf, geom = 'rect', alpha = 0.2)

enter image description here

关于r - ggplot : rearrange factor order and highlight area by `geom_rect` at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932758/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com