gpt4 book ai didi

r - 用不同颜色为散点图中每个象限的背景着色

转载 作者:行者123 更新时间:2023-12-04 10:39:56 31 4
gpt4 key购买 nike

假设我生成了这个散点图:

plot(x = runif(20,-10,10), y = runif(20,-10,10), xlim = c(-10,10), ylim = c(-10,10))
abline(h = 0, col = "black")
abline(v = 0, col = "black")

所以 abline将平面划分为四个笛卡尔象限。
我想用不同的颜色为每个象限的背景着色。分别为 1-4 象限说蓝色、红色、绿色和黄色。

任何的想法?

最佳答案

如果您喜欢 ggplot 解决方案:

df <- data.frame(x = runif(20,-10,10), y = runif(20,-10,10))
ggplot(df, aes(x,y)) +
annotate("rect", xmin = Inf, xmax = 0, ymin = Inf, ymax = 0, fill= "red") +
annotate("rect", xmin = -Inf, xmax = 0, ymin = -Inf, ymax = 0 , fill= "blue") +
annotate("rect", xmin = 0, xmax = Inf, ymin = 0, ymax = -Inf, fill= "yellow") +
annotate("rect", xmin = 0, xmax = -Inf, ymin = Inf, ymax = 0, fill= "green") +
geom_point() + xlim(-10,10)+ ylim(-10,10)

enter image description here

编辑:

@Spacedman:我不知道有些设备会遇到 Inf 的问题,这里不使用 Inf 的函数,还允许选择象限的交叉点和颜色
colquad <- function(plot, crossAt = 0, xlims = c(-10,10), ylims = c(-10,10), colours = c("blue", "red","yellow", "green")) {
#colours of rects are from left to right starting at the top
library(ggplot2)
plot <- plot + coord_cartesian(xlim = c(xlims[1],xlims[2]), ylim = c(ylims[1], ylims[2]))
plot +
annotate("rect", xmin = xlims[1], xmax = crossAt, ymin = ylims[2], ymax = crossAt, fill = colours[1]) +
annotate("rect", xmin = crossAt, xmax = xlims[2], ymin = crossAt, ymax = ylims[2], fill = colours[2]) +
annotate("rect", xmin = xlims[1], xmax = crossAt, ymin = ylims[1], ymax = crossAt , fill= colours[3]) +
annotate("rect", xmin = crossAt, xmax = xlims[2], ymin = crossAt, ymax = ylims[1], fill = colours[4]) +
geom_point()
}

使用它(制作之前的图表):
df <- data.frame(x = runif(20,-10,10), y = runif(20,-10,10))
plot <- ggplot(df, aes(x,y))
colquad(plot)

以及ggplot2优势的一个例子,将点的颜色更改为白色
colquad(plot) %+% geom_point(colour = "white")

关于r - 用不同颜色为散点图中每个象限的背景着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196315/

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