r - 如何在 ggplot2 中标记 geom_dotplot 的点?

标签 r ggplot2

假设我有这个简单的点图:

ggplot(mtcars, aes(hp)) +
  geom_dotplot(binwidth = 10, stackdir = 'center')

enter image description here

我想标记(一些)点。这不起作用:
ggplot(mtcars, aes(hp)) +
  geom_dotplot(binwidth = 10, stackdir = 'center') +
  geom_text(aes(label = rownames(mtcars)))
# Error: geom_text requires the following missing aesthetics: y

那么我如何访问 ygeom_dotplot 计算的值, 以便我可以将标签放置在正确的位置?

如果我设置 y = 0并使用 geom_text_repel我得到:
ggplot(mtcars, aes(hp)) +
  geom_dotplot(binwidth = 10, stackdir = 'center') +
  geom_text_repel(aes(label = rownames(mtcars)), box.padding = unit(2, 'lines'), y = 0)

enter image description here

这接近我想要的,除了所有的线段都指向 y = 0 .

编辑

我使用已接受答案的修改使其工作,该答案试图从设备尺寸推断 y 缩放量:
library(ggplot2)
library(ggrepel)

bw <- 10

p <- ggplot(mtcars, aes(hp)) +
geom_dotplot(binwidth = bw, stackdir = 'center')

built <- ggplot_build(p)
point.pos <- built$data[[1]]

# Order rows of mtcars by hp
idx <- order(mtcars$hp)
mtcars2 <- mtcars[idx,]

# Get the dimensions of the target device in pixels
size <- dev.size(units = 'px')
# Get the range of x and y domain values
extent <- with(built$layout$panel_params[[1]], abs(c(diff(x.range), diff(y.range))))
mtcars2$ytext <- (size[1] / size[2]) * (extent[2] / extent[1]) * point.pos$stackpos * bw
mtcars2$xtext <- point.pos$x

ggplot(mtcars2, aes(hp)) +
geom_dotplot(binwidth = bw, stackdir = 'center') +
geom_text_repel(
    aes(xtext, ytext, label = rownames(mtcars2)),
    box.padding = unit(.5 * size[1] * bw / extent[1], 'points'),
    color = 'red'
)

其中产生

enter image description here

这并不完美——这些段没有指向点的确切中心,因为整个图像的纵横比与面板的纵横比不同,但它非常接近。

最佳答案

下面提出的代码并不优雅。
它在微调比例因子后工作 scale.factor和情节尺寸。
我希望我的回答中包含的一些想法对解决您的问题有用。

library(ggplot2)

p <- ggplot(mtcars, aes(hp)) +
  geom_dotplot(binwidth = 10, stackdir = 'center')

# Get y-positions of points plotted by geom_dotplot
# Warning: these positions are not given
point.pos <- ggplot_build(p)$data[[1]]

# Order rows of mtcars by hp
idx <- order(mtcars$hp)
mtcars2 <- mtcars[idx,]

# scale.fact needs fine tuning 
# It is strictly connected to the dimensions of the plot
scale.fact <- 0.105
mtcars2$ytext <- point.pos$stackpos*scale.fact
mtcars2$xtext <- point.pos$x
lbls <- gsub(" ","\n",rownames(mtcars2))

png(file="myplot.png", width=4000, height=1400, res=300)
ggplot(mtcars2, aes(hp)) +
  geom_dotplot(binwidth = 10, stackdir = 'center', fill="#AAAAAA55") +
  geom_text(aes(label=lbls, x=xtext, y=ytext), size=2)
dev.off()

enter image description here

关于r - 如何在 ggplot2 中标记 geom_dotplot 的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991607/

相关文章:

r - 洗牌向量 - 样本()的所有可能结果?

r - 在 ggplot2 的 facet-grid/facet_wrap 中调整面板的相对空间

r - ggplot 中十分位数的低、中高颜色

r - 如何在 R 散点图中为特定值着色

c - 如何将 R 函数包装为 C 库

python - 优化股票交易脚本

r - 使用 lapply 函数的并行版本保留列表名称

r - R中的最小-最大归一化,根据另一列设置最小和最大组

r - geom_boxplot 中的极值标签

r - 更改火山图上的平滑度