使用R自带的数据集Titanic,绘制以下图形绘制Class和Survived两个变量的和线图和桑葚图
时间: 2024-04-01 07:33:07 浏览: 125
好的,下面是使用R语言绘制Titanic数据集中Class和Survived两个变量的和线图和桑葚图的代码和图形。
首先,我们需要安装并加载ggplot2和ggalluvial包:
```R
install.packages("ggplot2")
install.packages("ggalluvial")
library(ggplot2)
library(ggalluvial)
```
然后,我们加载Titanic数据集:
```R
data(Titanic)
```
接着,我们将数据集转换为适合绘制桑葚图的格式:
```R
titanic_alluvial <- as.data.frame(Titanic)
titanic_alluvial$Class <- rownames(Titanic)
titanic_alluvial <- reshape2::melt(titanic_alluvial, id.vars = "Class")
titanic_alluvial <- titanic_alluvial[titanic_alluvial$value > 0,]
```
现在,我们可以绘制和线图:
```R
ggplot(data = Titanic, aes(x = Class, y = Freq, fill = factor(Survived))) +
geom_bar(stat = "identity", position = "stack") +
labs(title = "Titanic: Class and Survived", x = "Class", y = "Frequency") +
scale_fill_discrete(name = "Survived", labels = c("No", "Yes")) +
theme_minimal()
```
图形如下所示:

接着,我们可以绘制桑葚图:
```R
ggplot(data = titanic_alluvial, aes(y = value, axis1 = Class, axis2 = variable, fill = factor(Survived))) +
geom_alluvium(aes(fill = factor(Survived)), width = 0.1) +
geom_stratum(width = 1/4, fill = "grey", color = "black") +
geom_text(aes(label = ifelse(is.na(value), "", value)), stat = "stratum", size = 3) +
scale_fill_discrete(name = "Survived", labels = c("No", "Yes")) +
theme_minimal()
```
图形如下所示:

希望这可以帮助您!
阅读全文
相关推荐
















