如何提取ggdist中geom_dots绘制的点图的点坐标?
问题描述
使用ggdist的geom_dots()绘制卡方分布点图后,想要提取每个点排列后的实际x、y坐标,但通过ggplot_build()提取的数据中,y值始终为0:
library(ggplot2) library(ggdist) # 生成点图 my_plot <- data.frame(x = rchisq(500, df = 10)) |> ggplot(aes(x = x)) + geom_dots(layout = "hex") # 提取数据,y值全为0 head(ggplot_build(my_plot)$data[[1]]) #> x PANEL group flipped_aes y datatype height ymin ymax thickness #> 1 8.712773 1 -1 TRUE 0 slab 1 0 1 1 #> 2 4.223199 1 -1 TRUE 0 slab 1 0 1 1 #> 3 7.535543 1 -1 TRUE 0 slab 1 0 1 1 #> 4 9.253599 1 -1 TRUE 0 slab 1 0 1 1 #> 5 20.435195 1 -1 TRUE 0 slab 1 0 1 1 #> 6 9.940869 1 -1 TRUE 0 slab 1 0 1 1 #> family side scale #> 1 topright 0.9 #> 2 topright 0.9 #> 3 topright 0.9 #> 4 topright 0.9 #> 5 topright 0.9 #> 6 topright 0.9

解决方法
geom_dots()的点布局计算是在grid绘图阶段完成的,并未提前存储在ggplot_build()的数据集里,因此直接提取无法得到实际y坐标,推荐两种可行方案:
方法1:直接调用ggdist::compute_dots()计算布局坐标
这是最直接的方式,跳过绘图环节,直接调用geom_dots()背后的布局计算函数:
library(ggplot2) library(ggdist) library(dplyr) # 生成原始数据 df <- data.frame(x = rchisq(500, df = 10)) # 计算点的布局坐标,参数与绘图时保持一致 dot_coords <- df |> compute_dots( aes(x = x), layout = "hex", scale = 0.9, side = "topright" ) # 查看包含布局后坐标的结果 head(dot_coords[, c("x", "y")])
返回的数据框中,x和y即为点排列后的实际数据坐标系坐标。
方法2:从ggplot的gtable中提取设备坐标
如果已生成绘图对象,可通过ggplot_gtable()获取grid层面的绘图元素,再提取点坐标:
# 生成绘图对象 my_plot <- df |> ggplot(aes(x = x)) + geom_dots(layout = "hex") # 转换为gtable对象 g <- ggplot_gtable(ggplot_build(my_plot)) # 定位点层的grob dot_grob_idx <- which(sapply(g$grobs, function(x) x$name) == "geom_dots") dot_grob <- g$grobs[[dot_grob_idx]] # 提取点的设备坐标(单位为npc,范围0-1) dot_coords <- dot_grob$children[[1]]$data # 查看设备坐标 head(dot_coords[, c("x", "y")])
注意:此方法获取的是绘图设备坐标系的数值,若需转换为原始数据坐标系,需结合坐标轴刻度范围进行换算。
内容的提问来源于stack exchange,提问作者Jake Thompson
相关产品推荐
相关产品推荐

