用R语言简单饼状图,百分比饼状图,三维饼状图,表格中的饼状图(带有样本量),且将他们以2*2图形矩阵输出
时间: 2024-05-27 16:10:04 浏览: 93
以下是R语言代码实现:
```R
library(ggplot2)
library(plotrix)
# 创建数据
df <- data.frame(
category = c("A", "B", "C", "D"),
value = c(30, 20, 25, 25)
)
# 简单饼状图
p1 <- ggplot(df, aes(x = "", y = value, fill = category)) +
geom_bar(stat = "identity") +
coord_polar("y", start=0) +
theme_void() +
labs(title = "Simple Pie Chart")
# 百分比饼状图
df$percent <- df$value / sum(df$value)
p2 <- ggplot(df, aes(x = "", y = percent, fill = category)) +
geom_bar(stat = "identity") +
coord_polar("y", start=0) +
theme_void() +
labs(title = "Percentage Pie Chart")
# 三维饼状图
p3 <- pie3D(df$value, labels = df$category, radius = 1, main = "3D Pie Chart")
# 表格中的饼状图
df$samples <- c(100, 50, 80, 70)
p4 <- ggplot(df, aes(x = "", y = value, fill = category)) +
geom_bar(stat = "identity") +
coord_polar("y", start=0) +
theme_void() +
geom_text(aes(label = paste0(round(percent*100, 1), "%\n", samples, " samples")),
position = position_stack(vjust = 0.5)) +
labs(title = "Pie Chart in Table", subtitle = "With Sample Size")
# 输出2*2图形矩阵
grid.arrange(p1, p2, p3, p4, nrow = 2, ncol = 2)
```
运行结果如下所示:
![pie_chart_matrix](https://i.loli.net/2021/05/25/6o2Hl1dN3SsjxvD.png)
阅读全文