如果你想让“背景”颜色一直延伸到图表边缘而不仅仅是极值点,可以采用以下变体方法:
ggplot(df) +
geom_rect(xmin = -Inf, xmax = 0, ymin = -Inf, ymax = 0, fill = "red") +
geom_rect(xmin = 0, xmax = Inf, ymin = -Inf, ymax = 0, fill = "blue") +
geom_rect(xmin = 0, xmax = Inf, ymin = 0, ymax = Inf, fill = "green") +
geom_rect(xmin = -Inf, xmax = 0, ymin = 0, ymax = Inf, fill = "yellow") +
geom_point(aes(x, y), size = 5)
![在此输入图片描述](https://istack.dev59.com/QUw55.webp)
编辑:透明度
加入 alpha=0.5
是“有效的”,但是使用 geom_rect
时,即使没有引用原始的 df
数据框,也会为每行 df
(在本例中为10次)绘制一个矩形。设置 alpha=0.01
显示了有透明度,但只有预期水平的1/10。正确的方法是使用注释来绘制矩形;注释仅绘制一次几何体,而不是针对原始数据框的每行都绘制一次。
ggplot(df) +
annotate("rect", xmin=-Inf, xmax=0, ymin=-Inf, ymax=0, fill="red", alpha=0.5) +
annotate("rect", xmin=0, xmax=Inf, ymin=-Inf, ymax=0, fill="blue", alpha=0.5) +
annotate("rect", xmin=0, xmax=Inf, ymin=0, ymax=Inf, fill="green", alpha=0.5) +
annotate("rect", xmin=-Inf, xmax=0, ymin=0, ymax=Inf, fill="yellow", alpha=0.5) +
geom_point(aes(x, y), size=5)
![在此输入图片描述](https://istack.dev59.com/wCyYg.webp)
geom_rect
吧? - joran