r - 如何绘制具有不同点颜色的散点图
问题描述
我需要模拟 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)
解决方案
首先创建一个具有 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:
推荐阅读
- selenium-webdriver - 无法开始新会话。可能的原因是远程服务器地址无效或浏览器启动失败。
- r - 次 y 轴中的特定数据
- python - 从windows到linux的conda环境
- amazon-s3 - 从 Amazon S3 获取文件到客户端 Web 应用程序 - 应该通过 Web API 发生吗?
- regex - 如何使用正则表达式从 Jmeter 中的响应标头中获取值
- javascript - jQuery LineControl Editor 在编辑模式下不起作用
- vaadin10 - Vaadin 流网格。如何从网格中获取数据/行
- vsto - hidpi 显示器上的 WebBrowser 控件缩放
- reactjs - 在 ReverseProxy 中处理位置 url
- node.js - 通过猫鼬将嵌套对象结果从 MongoDB 获取到节点环境时遇到麻烦