说我有这个简单的dotplot:
ggplot(mtcars, aes(hp)) +
geom_dotplot(binwidth = 10, stackdir = 'center')
我想标记(部分)这些要点。这不起作用:
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
那么如何才能访问为y
计算的geom_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)
这与我想要的很接近,除了所有线段都指向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'
)
哪个产生
它并不完美 - 细分不会指向点的确切中心,因为整个图像的纵横比与面板的纵横比不同,但它和#39;非常接近。
答案 0 :(得分:1)
下面提出的代码并不优雅
它在缩放因子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()
和绘图尺寸的微调之后起作用
我希望我的答案中包含的一些想法可以用来解决你的问题。
{{1}}