df <- data.frame( x = rnorm(120, c(0, 2, 4)), y = rnorm(120, c(1, 2, 1)), z = letters[1:3] ) 其中x 表示数据的横坐标,y 表示数据纵坐标,z 表示类别(a,b,c 三类)。 (1) 将 a,b,c 三类,画在一张图上,并用颜色区分类别。 (2) 将 a,b,c 三类,分别画在并列排放的三张图上(点用黑色)。 (3) 在(2)的基础上,每张子图上再加上每类点的质心(质心用颜色区分,size=4)。 (4) 将 a,b,c 三类,分别画在并列排放的三张图上(点用彩色)。每张子图上,其他 数据用灰色(”grey70”)显示。(例如:第一张子图 a 类数据是彩色,则 b 和 c 类 数据是灰色。)
时间: 2024-03-14 20:47:05 浏览: 53
好的,让我来回答你的问题。
1. 将 a,b,c 三类数据画在一张图上,用颜色区分类别,可以用如下代码实现:
```
library(ggplot2)
ggplot(df, aes(x = x, y = y, color = z)) + geom_point()
```
2. 将 a,b,c 三类数据分别画在并列排放的三张图上,可以用如下代码实现:
```
library(gridExtra)
p1 <- ggplot(subset(df, z == 'a'), aes(x = x, y = y)) + geom_point(color = 'black')
p2 <- ggplot(subset(df, z == 'b'), aes(x = x, y = y)) + geom_point(color = 'black')
p3 <- ggplot(subset(df, z == 'c'), aes(x = x, y = y)) + geom_point(color = 'black')
grid.arrange(p1, p2, p3, ncol = 3)
```
3. 在(2)的基础上,每张子图上再加上每类点的质心,可以用如下代码实现:
```
centroids <- aggregate(df[, c('x', 'y')], by = list(df$z), FUN = mean)
names(centroids)[1] <- 'z'
p1 <- ggplot(df, aes(x = x, y = y)) + geom_point(aes(color = z)) +
geom_point(data = subset(centroids, z == 'a'), aes(x = x, y = y, color = z), size = 4)
p2 <- ggplot(df, aes(x = x, y = y)) + geom_point(aes(color = z)) +
geom_point(data = subset(centroids, z == 'b'), aes(x = x, y = y, color = z), size = 4)
p3 <- ggplot(df, aes(x = x, y = y)) + geom_point(aes(color = z)) +
geom_point(data = subset(centroids, z == 'c'), aes(x = x, y = y, color = z), size = 4)
grid.arrange(p1, p2, p3, ncol = 3)
```
4. 将 a,b,c 三类数据分别画在并列排放的三张图上,其他数据用灰色显示。可以用如下代码实现:
```
p1 <- ggplot(df, aes(x = x, y = y)) +
geom_point(data = subset(df, z == 'a'), aes(color = z)) +
geom_point(data = subset(df, z != 'a'), color = 'grey70')
p2 <- ggplot(df, aes(x = x, y = y)) +
geom_point(data = subset(df, z == 'b'), aes(color = z)) +
geom_point(data = subset(df, z != 'b'), color = 'grey70')
p3 <- ggplot(df, aes(x = x, y = y)) +
geom_point(data = subset(df, z == 'c'), aes(color = z)) +
geom_point(data = subset(df, z != 'c'), color = 'grey70')
grid.arrange(p1, p2, p3, ncol = 3)
```
希望能回答到你的问题!
阅读全文