请给出能完成以下题目的R语言代码R自带的数据集iris 列出了3个物种(specie) 的萼片长(sepal.lngth)、曹片宽(spal. width)、花瓣长(ptal.length).花瓣宽(petalwidth) 4个变量的各50个样本数据、根据该数据集绘制以下图形. (1)绘制按species分组的轮廓图和雷达图. (2)绘制星图和脸谱图. (3)绘制聚类图和热图。
时间: 2023-10-04 15:13:51 浏览: 284
树懒种族分类数据集.rar
下面是能够完成以上要求的R语言代码:
```R
# 导入数据集iris
data(iris)
# (1) 按species分组的轮廓图和雷达图
library(ggplot2)
library(dplyr)
library(tidyr)
library(plotly)
# 轮廓图
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_density_2d() +
labs(x = "Sepal Length", y = "Sepal Width") +
ggtitle("Contour plot by species")
# 雷达图
iris %>%
pivot_longer(cols = -Species) %>%
ggplot(aes(x = name, y = value, group = Species, color = Species)) +
geom_point() +
geom_line() +
labs(title = "Radar plot by species") +
facet_wrap(~Species, ncol = 1) +
theme(legend.position = "top")
# (2) 星图和脸谱图
library(fmsb)
library(RColorBrewer)
# 星图
iris_scaled <- as.data.frame(scale(iris[, 1:4]))
iris_scaled$Species <- iris$Species
iris_scaled_melt <- melt(iris_scaled, id.vars = "Species")
iris_scaled_melt %>%
ggplot(aes(x = variable, y = value, group = Species, color = Species)) +
geom_point(size = 3) +
scale_color_brewer(palette = "Set1") +
scale_y_continuous(limits = c(-2, 3)) +
labs(title = "Star plot by species") +
coord_polar()
# 脸谱图
library(ggplot2)
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, col = Species)) +
geom_point() +
labs(title = "Facet plot by species") +
facet_grid(Species ~ .)
# (3) 聚类图和热图
library(ggplot2)
library(reshape2)
library(RColorBrewer)
# 聚类图
iris_cluster <- kmeans(iris[, 1:4], centers = 3, nstart = 20)
iris_cluster$cluster <- as.factor(iris_cluster$cluster)
iris_melt <- melt(iris, id.vars = "Species")
ggplot(data = iris_melt, aes(x = Species, y = value, fill = iris_cluster$cluster)) +
geom_boxplot() +
labs(title = "Cluster plot by species") +
scale_fill_brewer(palette = "Set1")
# 热图
library(gplots)
heatmap.2(as.matrix(iris[, 1:4]),
col = colorRampPalette(c("white", "blue"))(100),
trace = "none",
density.info = "none",
margins = c(10, 10),
dendrogram = "none")
```
希望这份代码能够帮助您完成绘制图形的任务。
阅读全文