用R语言分别制作 Sepal.Length、Sepal.Width、 Petal.Length、 Petal.Width 的 直方图(用密度值做代表 ,设置 prob =T),添加拟合的密度曲线, 四图同显。
时间: 2024-10-21 07:12:46 浏览: 30
R语言数据分析案例(一).docx
在R语言中,你可以使用`ggplot2`包来创建带密度曲线的直方图。假设你有一个名为`iris`的数据集,其中包含了`Sepal.Length`、`Sepal.Width`、`Petal.Length`和`Petal.Width`这些变量。下面是如何制作四张直方图并添加密度曲线的示例:
```r
# 加载所需的库
library(ggplot2)
# 假设data是iris数据集
data <- iris
# 创建四个直方图并添加密度曲线
p1 <- ggplot(data, aes(x = Sepal.Length)) +
geom_histogram(binwidth = 0.5, fill = "lightblue", color = "black", alpha = 0.6, position = "identity") +
geom_density(color = "red", size = 1, fill = NA, linetype = "dashed") +
labs(title = "Sepal.Length Density")
p2 <- ggplot(data, aes(x = Sepal.Width)) +
geom_histogram(binwidth = 0.2, fill = "lightblue", color = "black", alpha = 0.6, position = "identity") +
geom_density(color = "red", size = 1, fill = NA, linetype = "dashed") +
labs(title = "Sepal.Width Density")
p3 <- ggplot(data, aes(x = Petal.Length)) +
geom_histogram(binwidth = 1, fill = "lightblue", color = "black", alpha = 0.6, position = "identity") +
geom_density(color = "red", size = 1, fill = NA, linetype = "dashed") +
labs(title = "Petal.Length Density")
p4 <- ggplot(data, aes(x = Petal.Width)) +
geom_histogram(binwidth = 0.5, fill = "lightblue", color = "black", alpha = 0.6, position = "identity") +
geom_density(color = "red", size = 1, fill = NA, linetype = "dashed") +
labs(title = "Petal.Width Density")
# 合并四个图形到一个画布
grid.arrange(p1, p2, p3, p4, ncol = 2)
```
这会创建一个网格布局,每个直方图都有其对应的密度曲线。`geom_histogram`用于创建直方图,`geom_density`用于添加密度曲线。
阅读全文