更多教程请浏览我的博客地址R语言画图之图片局部放大
在处理图片的时候,有时候需要将局部图片放大,比如病理的免疫组化的图,那么如何实现R的局部放大呢?
记录一个蛮有趣的功能,选择性放大图片的部分区域。处理密集分布数据应该很有效,示例数据不是很合适。
示例数据演示
我们使用自带测试数据iris,绘制Petal.Length
与Petal.Width
相关散点图。
加载数据
data(iris)
## 显示前10行数据
iris[1:10, ]
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3.0 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.3 | 0.2 | setosa |
4.6 | 3.1 | 1.5 | 0.2 | setosa |
5.0 | 3.6 | 1.4 | 0.2 | setosa |
5.4 | 3.9 | 1.7 | 0.4 | setosa |
4.6 | 3.4 | 1.4 | 0.3 | setosa |
5.0 | 3.4 | 1.5 | 0.2 | setosa |
4.4 | 2.9 | 1.4 | 0.2 | setosa |
4.9 | 3.1 | 1.5 | 0.1 | setosa |
绘制散点图
library(ggplot2)
# 定义主题
theme <- theme_bw() + theme(plot.title = element_text(hjust = 0.5, size = 22), axis.text.x = element_text(hjust = 0.5,
size = 18), axis.text.y = element_text(hjust = 0.5, size = 18), axis.title.y = element_text(size = 18),
axis.title.x = element_text(size = 18), legend.text = element_text(size = 18),
legend.title = element_blank(), legend.position = c(0.85, 0.2), legend.background = element_blank())
# 绘图
p1 <- ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point(aes(color = Species),
size = 2) + scale_color_manual(values = c("#2fa1dd", "#e6b707", "#f87669")) +
theme
p1 <- p1 + geom_smooth(method = "lm", formula = y ~ x, se = TRUE, show.legend = FALSE,
color = "#66C2A5")
p1
默认散点图
安装并加载ggmagnify
ggmagnify目前还没有被CRAN收录,目前有两种安装方式:GitHub和r-universe
# 如果可以访问GitHub
# remotes::install_github("hughjonesd/ggmagnify")
# 国内可通过r-universe进行安装
install.packages("ggmagnify", repos = c("https://hughjonesd.r-universe.dev",
"https://cloud.r-project.org"))
## 加载ggmagnify
library(ggmagnify)
指定局部放大区域
指定局部放大区域的话,我们需要定义相应的坐标,比如原图需要放大的区域坐标,以及将放大后的局部图插入到原图的位置坐标。
指定放大坐标范围与放大后图片放置区域,顺序为xmin
, xmax
, ymin
, ymax
target = c(4.6, 5.4, 1.5, 2) ##目标区域的x轴为4.6-5.4,y轴为4.1-5.2
insert = c(1.2, 3, 1.3, 2.5) ##插入区域的x轴为1.2-3,y轴为1.3-2.5
放大局部区域只需要一步函数geom_magnify()
p2 <- p1 + geom_magnify(from = target, to = insert)
p2
局部放大散点图
我们还可以放大局部区域(添加坐标轴),并自定义轮廓线颜色
p3 <- p1 + geom_magnify(from = target, to = insert, proj = "facing", colour = "#0066fe",
linewidth = 0.5, axes = TRUE)
p3
自定义局部放大图