使用r自带的数据集Titianic绘制以下图形1.绘制Sex和Class的并列条形图和堆叠条形图,并为条形图添加频数标签2.绘制Sex和Class热图
时间: 2024-12-23 09:20:30 浏览: 4
当然可以。在R语言中,我们可以使用`ggplot2`库来创建各种美观的图表,包括条形图和热图。首先,我们需要加载必要的数据集和包。
1. **绘制性别和等级的并列条形图和堆叠条形图**:
- 并列条形图(side-by-side bar chart):
```R
library(ggplot2)
data(Titanic) # 加载Titanic数据集
p1 <- ggplot(Titanic, aes(x = Class, fill = Sex)) +
geom_bar(position = "dodge", stat = "count") +
labs(title = "Titanic乘客按性别和等级分类",
x = "船舱等级", y = "人数", fill = "性别") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
print(p1)
```
- 堆叠条形图(stacked bar chart):
```R
p2 <- ggplot(Titanic, aes(x = Class, y = ..prop.., fill = Sex)) +
geom_bar(stat = "identity") +
labs(title = "Titanic乘客按性别分层的百分比",
x = "船舱等级", y = "%", fill = "性别") +
scale_fill_manual(values = c("male" = "blue", "female" = "pink")) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
print(p2)
```
2. **绘制性别和等级的热图**:
R中的`seaborn`库更适合创建热图,但如果要用基础的`ggplot2`,需要先计算一些频率数据:
```R
# 先计算每个组合的频数
counts <- table(Titanic$Sex, Titanic$Class)
# 创建数据框以便于绘图
df_counts <- as.data.frame(cbind(Sex = levels(counts[,1]),
Class = levels(counts[,2]),
Count = unlist(counts)))
# 热图(假设ggplot2不直接支持)
library(reshape2) # 或使用tidyverse的pivot_wider
df_pivot <- melt(df_counts, id.vars = c("Sex", "Class"), variable.name = "Type")
p3 <- ggplot(df_pivot, aes(x = Class, y = Sex, fill = value)) +
geom_tile() +
scale_fill_viridis(discrete = TRUE) +
labs(title = "Titanic乘客性别与等级的交叉计数",
x = "船舱等级", y = "性别", fill = "计数") +
theme_minimal()
print(p3)
```
阅读全文