简介
书接adjustText实践——调整matplotlib散点图标签,避免重复
上文中,matplotlib+adjustText对于我的实例来说并没有起到很好的效果。所以,博主决定在R中利用gglot2+ggrepel绘制,期待效果。
操作过程
博主不常使用R,在此过程中详细记录每一步骤,以作备忘。
1. R读取数据(openxlsx)
library(openxlsx)
fossils = read.xlsx("D://Work_Space/mahonia/1-化石记录/2023-3-17-Mahonia_fossils_leaf.xlsx")
2. 绘制散点图(ggplot2)
2.1 快速绘制散点图(plot)
library(ggplot2)
plot(fossils$Lon, fossils$Lat)
2.2 geom_point()
library(gcookbook)
library(dplyr)
ggplot(data = fossils %>% select(Lon, Lat), aes(x=Lon, y=Lat)) + geom_point()
2.3 分组展示(分型和年龄)
library(openxlsx)
fossils <- read.xlsx("D://Work_Space/mahonia/1-化石记录/2023-3-17-Mahonia_fossils_leaf.xlsx")
simple_fossils <- fossils %>% select(Genus, Name, Epoch, Lon, Lat, Group)
library(ggplot2)
# plot(fossils$Lon, fossils$Lat)
library(gcookbook)
library(dplyr)
ggplot(data = simple_fossils %>% select(Lon, Lat, Group, Epoch), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_point()
2.4 添加文本注释(geom_text())
ggplot(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_point() + geom_text(aes(label = Name), size = 2)
3. 优化文本注释位置(ggrepel)
library(ggrepel)
ggplot(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_point() + geom_text_repel(aes(label = Name), size = 3)
可以看到有许多标签没有显示出来。
尝试减小字体
ggplot(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_point() + geom_label_repel(aes(label = Name), size = 1)
根据警示信息,增加max.overlaps
ggplot(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_point() + geom_label_repel(aes(label = Name), size = 2, max.overlaps = 30)
效果也不行,还是挤在一起。
4. 绘制世界地图
4.1 地图
world <- map_data("world")
world_map <- ggplot() + geom_map(data = world, map=world, aes(x=long, y=lat, map_id=region),color = "black", fill = "lightgray", size = 0.1)+scale_x_continuous(breaks = seq(-180, 210, 45), labels = function(x){paste0(x, "°")}) +
scale_y_continuous(breaks = seq(-60, 100, 30), labels = function(x){paste0(x, "°")})
world_map
4.2 散点地图
world_map + geom_point(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch))
4.2 合理调整文本
world_map + geom_point(data = simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, shape=Group, color=Epoch)) + geom_label_repel(data=simple_fossils %>% select(Lon, Lat, Group, Epoch, Name), aes(x=Lon, y=Lat, label=Name, color=Epoch,fontface="italic"), size=2, max.overlaps = 100, box.padding = 0.4, label.padding = 0.1)
文章来源:https://www.toymoban.com/news/detail-410813.html
后记
经过一番努力,达到的效果比python绘图要好一些。但是在保存图片时却不如python。后面再努努力吧。文章来源地址https://www.toymoban.com/news/detail-410813.html
到了这里,关于R语言实践——ggplot2+ggrepel绘制散点+优化注释文本位置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!