首先,指定分类变量顺序的方法ggplot
是重新排序它的级别data.frame
。其次,要在我们可以使用的任何绘图上突出显示一个区域geom_rect
。这里需要注意的是,不要将数据传递给geom_rect
,否则它不允许我们设置alpha
,因此网格线将不可见。现在有2种情况:
- 如果我们将数据传递给
geom_rect
(或到顶层ggplot()
),订单与中的一致data.frame
,但正如我提到的,矩形不会是透明的
- 如果我们只将数据传递给
geom_point
图层,ggplot 按字母顺序重新排列离散变量
如何同时拥有这两个标准,即具有预定义的顺序并在所需位置具有透明矩形?
奖金问题:如何在离散变量处有一个矩形,其边缘位于网格线之间,即通过调整0.5
? vjust
and hjust
这里不使用参数(正如警告告诉我们的那样)。以及如何使矩形填充整个垂直空间(为此我们需要定义ymax
as the 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
)
)