首页 > 解决方案 > 如何绘制具有不同点颜色的散点图

问题描述

我需要模拟 400 个观测值对,并在 R 中用一组不同的颜色绘制观测值对的 X1、X2 的散点图。我使用了下面的代码,但我认为它不正确。

group <- rbinom(200, 1, 0.3) + 0                  # Create grouping variable

group_pch <- group                                # Create variable for symbols
group_pch[group_pch == 1] <- 16
group_pch[group_pch == 0] <- 16

group_col <- group                                # Create variable for colors
group_col[group_col == 1] <- "red"
group_col[group_col == 0] <- "green"

plot(x, y,                                        # Scatterplot with two groups
     pch = group_pch,
     col = group_col)

标签: r

解决方案


首先创建一个具有 400 个 x 和 y 值的数据框,此处为 (X1, X2)。我使用生成的随机数创建了这些值rnorm(),详情请参阅help(rnorm)。然后我创建了第三个变量,higher如果相应的 x (X1) 值大于 3(平均值),lower则返回标签,否则返回标签。再次,请参阅help(cut)以获取更多信息。

最后,可以通过plot(x = df$X1, y = df$X2)一个简单的散点图来可视化。使用参数col = df$Color,点根据 用颜色分隔breaks = c(-Inf, 3, +Inf)

不幸的是,从您的问题中不清楚需要多少颜色/分隔/组/...,以及应该使用哪个规则来区分它们。

# if you need to submit your code: 
set.seed(1209) # to make results reproducible; see: 
# ?set.seed()

# Create dataframe with 400 x and y-values 
df <- data.frame(
  X1 = rnorm(400, mean=3, sd=1),
  X2 = rnorm(400, mean=5, sd=3))

# Create new variable (color) for plotting
df$Color <- cut(df$X1, breaks = c(-Inf, 3, +Inf), 
                labels = c("lower", "higher"), 
                right = FALSE)
# Plot #1
# Plot the points and differentiate X1 smaller/greater 3 by color
plot(x = df$X1, y = df$X2, 
     col = df$Color, 
     main = "Plot Title", 
     pch = 19, cex = 0.5)

如果您被要求使用特定颜色,请执行以下操作:

  # class(df$Color) # returns factor - perfect!
  preferredColors <- c("red", "green")[df$Color]
  # you need as many colors as labels, here 2 (lower, higher)

  # Plot #2
  plot(x = df$X1, y = df$X2, 
       col = preferredColors, 
       main = "Plot Title", 
       xlab = "Description of x-axes",
       ylab = "Description of y-axes",
       pch = 19, cex = 0.5)

仅作说明;仅复制以前的代码:

# output first three rows of the df for inspection purpose: 
head(df, n=3)
#>         X1         X2  Color
#> 1 2.450875  5.6721845  lower
#> 2 5.582115  4.8569917 higher
#> 3 2.324129 -0.3660018  lower

由 reprex 包于 2021-09-12 创建 (v2.0.1)

输出,情节#2:

在此处输入图像描述


推荐阅读