如何将颜色更改为散点图中的仅两个特定数据点?

时间:2020-09-08 18:17:21

标签: r

enter image description here enter image description here

我正在RStudio中处理散点图,并试图将仅两个数据点的颜色从黑色更改为红色。我已经尝试过像points(bradyscore[-2.0], sum[11.6], col="red")这样的命令,但是它要么带有错误代码,说明变量的长度不同(它们不应为长度,因为它是数据点的坐标),否则它会更改我的整个图更改点的形状,标题和轴。我还想给两个特定的数据点着色,而不仅仅是一个。 (bradyscore = x和sum = y)(如果有任何用处),则有一个分类变量,它是每个数据点的标签。图为我现在拥有的绘图,除了两个数据点的颜色:DC(50,13.9)和Louisiana(-2.0,11.6),我不想更改该绘图的任何内容。总共有51个数据点。

2 个答案:

答案 0 :(得分:1)

您所做的问题

隔离向量的一个元素时,必须提供其在向量中的位置:

x <- 11:20
x[5]
# [1] 15

x[15]
# [1] NA
# -> there is no 14th element of x, which is of length 10.

在您的情况下,-2.011.6转换为整数并用作索引:

x[-2.0]
# [1] 11 13 14 15 16 17 18 19 20
# -> removed 2nd element
x[11.6]
# [1] NA
# -> kept the 11th element (which doesn't exist here)

这里我猜您的xy变量是bradyscoresum?因此,您需要在这些向量中找到Louisiana的位置,并将该位置用作下标。


让我们从一些与您拥有的数据相似的数据开始:

library(tidyverse)
Guns_data <- tribble(~jurisdiction, ~sum, ~bradyscore,
                     "D.C.",        13.9,        50.0,
                     "Delaware",     6.2,        35.4,
                     "Florida",      5.3,         3.0,
                     "Kentucky",     4.9,        -3.5,
                     "Louisiana",   16.6,        -2.0)

示例1:子帧数据

我们可以直接从jurisdiction中选择要着色的值:

jurisd_to_color <- c("Louisiana", "Delaware")

使用ggplot2

我们可以添加一列来指示每个辖区所属的颜色组:

Guns_data <- mutate(Guns_data,
                    my_colors = if_else(jurisdiction %in% jurisd_to_color,
                                    "to_plot_in_red",
                                    "to_plot_in_black"))

# then plot it
ggplot(Guns_data, aes(x=bradyscore,y=sum,color=my_colors)) +
  geom_point(shape=15) +
  ggrepel::geom_label_repel(aes(label=jurisdiction)) +
  scale_color_manual(values=c("red","black")) +
  theme_classic()

以R为底

我们再次添加一列以绘制颜色:

Guns_data$my_colors <- ifelse(Guns_data$jurisdiction %in% jurisd_to_color,
                          "red",
                          "black")

# Now plot the points
plot(x    = Guns_data$bradyscore,
     y    = Guns_data$sum,
     col  = Guns_data$my_colors,
     pch  = 15,
     xlab = "Brady Score",
     ylab = "Gun Deaths")

# and the labels
text(x      = Guns_data$bradyscore,
     y      = Guns_data$sum,
     labels = Guns_data$jurisdiction,
     col    = Guns_data$my_colors,
     pos=4)

示例2:具有坐标

我们可以在黑色背景上绘制整个内容,而不是在数据框中添加一列,然后用红色指示要超标的点的坐标。在这里,我们将路易斯安那州绘制为红色,因此x=-2y=16.6

使用ggplot2

我们向geom_point添加了第二个调用,该调用将在现有点上绘图:

ggplot(Guns_data, aes(x=bradyscore,y=sum)) +
  geom_point(shape=15) +
  ggrepel::geom_label_repel(aes(label=jurisdiction)) +
  geom_point(aes(x=-2.0,y=16.6),
             color="red", shape=15) +
  theme_classic()

以R为底

我们可以使用points()来绘制现有图形的顶部:

plot(x    = Guns_data$bradyscore,
     y    = Guns_data$sum,
     pch  = 15,
     xlab ="Brady Score",
     ylab ="Gun Deaths")

points(x   = -2,
       y   = 16.6,
       col = "red",
       pch = 15)

您可以使用text进行同样的操作以覆盖黑色文本。

答案 1 :(得分:1)

points()函数中,只需给出要重新着色或重塑形状的点的坐标

points(c(50,-2),c(13.9,11.6),col="red")