如何在ggplot2散点图的标签中添加completion数据?
问题:如何在散点图标签中添加completion数据?
我有一个示例数据集df:
df <- data.frame( title = c("Whispers in the Dark", "The Silent Shadows", "Echoes of the Forgotten", "The Vanishing Path", "Haunted Reflections"), downloads = c(84902, 78267, 81463, 102784, 112948), age_in_days = c(191, 184, 177, 170, 163), completion = c(59, 57, 43, 65, 71) )
我已使用以下代码绘制了age_in_days与downloads的散点图:
library(ggplot2) library(ggrepel) ggplot(df, aes(x = age_in_days, y = downloads)) + geom_point() + geom_text_repel(aes(label = title), size = 3, box.padding = 0.35, point.padding = 0.3) + theme_minimal()
当前图表的标题标签仅显示作品名称,我希望在每个标签旁添加completion数据(如"Haunted Reflections (71)"形式),请问如何在现有散点图中实现该可视化需求?
解决方案
你可以通过以下两种简单方法实现需求:
方法1:直接在geom_text_repel中拼接标签
无需修改原始数据集,直接在aes(label)参数里用paste()函数把标题和完成率拼接成目标格式:
library(ggplot2) library(ggrepel) ggplot(df, aes(x = age_in_days, y = downloads)) + geom_point() + geom_text_repel( aes(label = paste(title, "(", completion, ")", sep = "")), # 生成"标题(数值)"格式 size = 3, box.padding = 0.35, point.padding = 0.3 ) + theme_minimal()
如果想要标题和括号之间留空格,把sep = ""换成sep = " ",就能得到"标题 (数值)"的样式。
方法2:先在数据框中预先生成标签列
如果后续需要反复使用这个标签格式,可以先给df新增一列存储拼接后的文本,再用该列作为标签:
# 添加新的标签列 df$label_text <- paste(df$title, "(", df$completion, ")", sep = "") # 绘制图表 ggplot(df, aes(x = age_in_days, y = downloads)) + geom_point() + geom_text_repel( aes(label = label_text), size = 3, box.padding = 0.35, point.padding = 0.3 ) + theme_minimal()
两种方式都能实现你想要的标签效果,根据实际需求选择即可。
内容的提问来源于stack exchange,提问作者Jay Bee
相关产品推荐
相关产品推荐

