ggplot2绘制散点图(一)基本绘制以及美化
发布网友
发布时间:2024-09-30 17:31
我来回答
共1个回答
热心网友
时间:2024-10-07 05:33
本文介绍使用ggplot2绘制散点图的基本方法和美化技巧,以iris数据集为例。首先,确保安装并加载ggplot2包。
通过以下代码导入iris数据集并绘制花萼长度与花瓣长度的散点图:
data = iris
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point()
若想添加线性回归线,可以修改代码为:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point() + geom_smooth(method = lm)
默认情况下,线性回归线的置信区间为95%。可通过调整level参数设置置信水平,例如:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point() + geom_smooth(method = lm, level = 0.99)
绘制不同类型的回归线,如平滑回归线,并调整颜色和线条,如:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point(colour = "#990000") + geom_smooth(method = loess, level = 0.99, colour = "#009900")
通过调整点的大小、颜色、形状和填充颜色,可以进一步美化散点图。使用`size`参数控制点大小,`colour`参数控制颜色,`shape`参数指定形状,`fill`参数定义填充颜色。
展示点型的不同表示,例如使用数字或字符串进行设置:
lab = c(0:25) sha = c(1:26) shap = data.frame(lab = lab, sha = sha) ggplot(data = shap, aes(x = 1:26, y = sha)) + geom_point(shape = lab, size = 3) + geom_text(aes(label = lab, vjust = -1.5)) + ylim(0, 28) + ggtitle("数字代表的点型")
设置单一颜色、点型和大小的散点图:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point(colour = "#339911", shape = 19, size = 1.5)
通过颜色渐变显示数据的连续变化,如:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length, colour = Sepal.Length)) + geom_point()
注意颜色设置的顺序。将参数color放在第二行,结果将不同:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length)) + geom_point(colour = data$Sepal.Length)
应用调色板,如灰度调色板或Colorbrewer调色板,需将数据转换为离散类型:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length, colour = as.factor(Sepal.Length))) + geom_point() + scale_color_grey(start = 1, end = 0.5)
使用连续渐变调色板,如:
ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length, colour = Sepal.Length)) + geom_point() + scale_color_gradient(low = "green", high = "#990000")
实现三色和多色渐变:
library(scales) ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length, colour = Sepal.Length)) + geom_point() + scale_color_gradient2(low = muted("green"), mid = "orange", high = muted("red"), midpoint = 6)
应用颜色和填充调色板,并设置图形坐标和标题:
library(RColorBrewer) ggplot(data = data, aes(x = Petal.Length, y = Sepal.Length, colour = Species, shape = Species, fill = Species)) + geom_point(size = 2) + scale_color_brewer(palette = "Spectral") + scale_fill_brewer(palette = "Spectral") + theme_dark() + ggtitle("散点图绘制") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(1, 7, 0.5)) + scale_y_continuous(breaks = seq(4, 8, 0.5))