使用R自带的数据集Titanic绘制绘制Class和Survived的气球图、热图和南丁格尔玫瑰图
时间: 2023-10-16 17:09:51 浏览: 326
好的,我可以为您提供代码来绘制Titanic数据集的Class和Survived的气球图、热图和南丁格尔玫瑰图。请注意,需要安装`ggplot2`和`ggforce`包来绘制气球图和南丁格尔玫瑰图。
首先,加载数据集并准备数据:
```R
library(ggplot2)
library(ggforce)
# 加载数据集
data(Titanic)
# 将数据转换为数据框
df <- as.data.frame(Titanic)
# 将数据格式转换为适合绘制气球图和南丁格尔玫瑰图的格式
df <- df %>%
mutate(Survived = factor(Survived),
Class = factor(Class),
n = as.numeric(Freq))
```
接下来,绘制气球图:
```R
# 绘制气球图
ggplot(df, aes(x = Class, y = Survived, size = n, fill = Survived)) +
geom_circle(aes(r = n/2), alpha = 0.8, color = "white", show.legend = FALSE) +
scale_size(range = c(0, 1), guide = FALSE) +
labs(title = "Titanic Survival by Class", x = "Class", y = "Survived") +
theme_void() +
theme(plot.title = element_text(hjust = 0.5))
```
绘制热图:
```R
# 绘制热图
ggplot(df, aes(x = Class, y = Survived, fill = n)) +
geom_tile(color = "white") +
scale_fill_gradient(low = "white", high = "steelblue") +
labs(title = "Titanic Survival by Class", x = "Class", y = "Survived") +
theme(plot.title = element_text(hjust = 0.5))
```
绘制南丁格尔玫瑰图:
```R
# 绘制南丁格尔玫瑰图
ggplot(df, aes(x = Class, y = n, fill = Survived)) +
geom_bar_polar(aes(y = n/4, theta = -2*pi*(Class-1)/4 + pi/2), stat = "identity") +
scale_fill_manual(values = c("#E7B800", "#FC4E07")) +
labs(title = "Titanic Survival by Class", x = "Class", y = "Count", fill = "Survived") +
theme(plot.title = element_text(hjust = 0.5))
```
希望这些代码可以帮助您绘制出Titanic数据集的Class和Survived的气球图、热图和南丁格尔玫瑰图。
阅读全文