英文:
Altering the colour of a specific point in a ggplot
问题
我想更改数据框中特定点的颜色,注意我并没有绘制条件。
library(ggplot2)
colpf <- c(0, 0, 0, 1, 1, 1, 2, 2, 2)
coldf <- c(0, 1, 2, 0, 1, 2, 0, 1, 2)
x <- seq(0, 8, 1)
y <- seq(0, 8, 1)
df <- data.frame(colpf, coldf, x, y)
ggplot(data = df) +
geom_point(aes(x = x, y = y))
我想将colpf等于1且coldf等于1的点(例如,红色)设为特殊颜色。在这种情况下,我相信这将有一个简单的解决方案,然而我的思维似乎无法理解它。谢谢。
英文:
I would like to change the colour of a specific point in a dataframe, note that I am not plotting the condition.
library(ggplot2)
colpf <- c(0,0,0,1,1,1,2,2,2)
coldf <- c(0,1,2,0,1,2,0,1,2)
x <- seq(0,8,1)
y <- seq(0,8,1)
df <- data.frame(colpf,coldf,x,y)
ggplot(data = df) +
geom_point(aes(x=x,y = y))
I would like to make the point which corresponds to colpf = 1 and coldf=1, say, red. In this case I believe it would be the point (4,4). I believe this will have a simple solution however my mind cannot seem to grasp it. Thank you.
答案1
得分: 3
创建一个指示变量,用于指示条件是否满足。将颜色美学映射到该变量,并使用 scale_*
层调整颜色。
library(ggplot2)
colpf <- c(0, 0, 0, 1, 1, 1, 2, 2, 2)
coldf <- c(0, 1, 2, 0, 1, 2, 0, 1, 2)
x <- seq(0, 8, 1)
y <- seq(0, 8, 1)
df <- data.frame(colpf, coldf, x, y)
i <- with(df, colpf == 1 & coldf == 1)
i
#> [1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
ggplot(data = df) +
geom_point(aes(x = x, y = y, color = i), show.legend = FALSE) +
scale_color_manual(values = c(`FALSE` = "black", `TRUE` = "red"))
创建于2023-02-23,使用 reprex v2.0.2
英文:
Create an indicator variable telling if the condition is met. Map the color aesthetic to that variable and adjust the colors with a scale_*
layer.
library(ggplot2)
colpf <- c(0,0,0,1,1,1,2,2,2)
coldf <- c(0,1,2,0,1,2,0,1,2)
x <- seq(0,8,1)
y <- seq(0,8,1)
df <- data.frame(colpf,coldf,x,y)
i <- with(df, colpf == 1 & coldf == 1)
i
#> [1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
ggplot(data = df) +
geom_point(aes(x = x, y = y, color = i), show.legend = FALSE) +
scale_color_manual(values = c(`FALSE` = "black", `TRUE` = "red"))
<!-- -->
<sup>Created on 2023-02-23 with reprex v2.0.2</sup>
答案2
得分: 1
尽管Rui Barradas的答案更加优雅,如果您不想进行条件判断或无法确定特定条件,一个替代方法是通过索引特定兴趣点来实现:
ggplot() +
geom_point(data = df[-5,], aes(x = x, y = y), show.legend = FALSE) +
geom_point(data = df[5,], aes(x = x, y = y), color = "red", show.legend = FALSE)
英文:
Although Rui Barradas's answer is more elegant, if you didn't want to condition or could not determine a specific condition an alternative is to do this by indexing the specific point of interest:
ggplot() +
geom_point(data = df[-5,], aes(x = x, y = y), show.legend = FALSE) +
geom_point(data = df[5,], aes(x = x, y = y), color = "red", show.legend = FALSE)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论