使用packcircles+ggplot制作气泡图的3个技术问题及解决诉求
Packcircles + ggplot气泡图问题解决方法
1. 导出后圆形变椭圆形的解决
气泡图必须用等比例坐标系,否则圆形会被拉伸变形。在ggplot中添加coord_fixed()强制宽高比一致,同时用ragg导出时指定相近的宽高尺寸,避免拉伸:
# 导出时设置等比例尺寸 ragg::agg_png("bubble_plot.png", width = 800, height = 800, res = 100) ggplot(...) + ... + coord_fixed() # 关键:强制等比例 dev.off()
2. 气泡内文本适配尺寸
不要固定字号,而是根据气泡的半径(或面积)动态调整字体大小。直接在geom_text里将size映射到气泡半径,再用scale_size_continuous控制字号范围:
# 假设布局数据包含radius列 ggplot(layout_df, aes(x, y)) + geom_circle(aes(r = radius, fill = Segment)) + # 映射size到radius,设置合理的字号范围 geom_text(aes(label = Label, size = radius), color = "white", fontface = "bold") + scale_size_continuous(range = c(5, 18)) # 最小到最大字号,按需调整
如果需要更精准适配,可手动计算字号,比如size = radius * 2,再根据实际效果微调系数。
3. 图例显示Segment而非id编号
packcircles生成的布局数据里的id是原始数据的行号,需要把原始数据的Segment字段合并到布局数据中,再用Segment作为填充/颜色的映射:
# 假设原始数据是data,包含Segment和size列 library(packcircles) # 生成布局 layout <- circleProgressiveLayout(data$size, sizetype = "area") # 转换为顶点数据,并合并Segment layout_df <- circleLayoutVertices(layout, npoints = 50) %>% left_join(data %>% mutate(id = row_number()), by = "id") # 合并原始数据的Segment # 绘图时用Segment映射fill ggplot(layout_df, aes(x, y)) + geom_polygon(aes(group = id, fill = Segment), color = "black") + ...
完整修正代码示例
library(ggplot2) library(packcircles) library(dplyr) library(ragg) # 模拟原始数据 data <- tibble( Segment = c("A类", "B类", "C类", "D类", "E类"), size = c(100, 60, 30, 20, 10) # 气泡面积 ) # 生成布局并合并Segment layout <- circleProgressiveLayout(data$size, sizetype = "area") layout_df <- circleLayoutVertices(layout, npoints = 50) %>% left_join(data %>% mutate(id = row_number()), by = "id") # 绘图+导出 ragg::agg_png("fixed_bubble_plot.png", width = 800, height = 800, res = 100) ggplot(layout_df, aes(x, y)) + geom_polygon(aes(group = id, fill = Segment), color = "black", alpha = 0.8) + geom_text(aes(label = Segment, size = radius), color = "white", fontface = "bold") + scale_size_continuous(range = c(6, 16)) + coord_fixed() + # 强制等比例,避免椭圆 theme_void() + # 去掉多余元素 theme(legend.position = "right") dev.off()
内容的提问来源于stack exchange,提问作者Edwin Acuña
相关产品推荐
相关产品推荐

