Created
August 17, 2021 23:14
-
-
Save antonkratz/8f8c077b0d236033889b1650629a0000 to your computer and use it in GitHub Desktop.
Getting coordinates for the label locations from ggrepel, Cytoscape, https://stackoverflow.com/questions/45065567/getting-coordinates-for-the-label-locations-from-ggrepel, tested and works under R 4.1.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012, 0.9055, 1.3307) | |
y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542, 0.9717, 0.9357) | |
ShortSci = c("MotAlb", "PruMod", "EriRub", "LusMeg", "PhoOch", "PhoPho", | |
"SaxRub", "TurMer", "TurPil", "TurPhi") | |
df <- data.frame(x = x, y = y, z = ShortSci) | |
library(ggplot2) | |
library(ggrepel) | |
p1 <- ggplot(data = df, aes(x = x, y = y)) + theme_bw() + | |
geom_text_repel(aes(label = z), | |
box.padding = unit(0.45, "lines")) + | |
geom_point(colour = "green", size = 3) | |
x11(width=7,height=7) | |
p1 | |
# Get x and y plot ranges | |
ggp1 <- ggplot_build(p1) | |
xrg <- ggp1$layout$panel_params[[1]]$x.range | |
yrg <- ggp1$layout$panel_params[[1]]$y.range | |
library(grid) | |
grid.force() | |
kids <- childNames(grid.get("textrepeltree", grep = TRUE)) | |
# Function: get the x and y positions of a single ggrepel label | |
get.xy.pos.labs <- function(n) { | |
grb <- grid.get(n) | |
data.frame( | |
x = xrg[1]+diff(xrg)*convertX(grb$x, "native", valueOnly = TRUE), | |
y = yrg[1]+diff(yrg)*convertY(grb$y, "native", valueOnly = TRUE) | |
) | |
} | |
# Get positions of all ggrepel labels | |
dts <- do.call(rbind, lapply(kids, get.xy.pos.labs)) | |
dts$lab <- df$z | |
print(dts) | |
# Plot labels using the positions calculated using get.xy.pos.labs | |
p2 <- ggplot(data = df, aes(x = x, y = y)) + theme_bw() + | |
geom_text(aes(x=x,y=y, label=lab), data=dts, col="red", inherit.aes=F)+ | |
geom_point(colour = "green", size = 3) | |
x11(width=7,height=7) | |
p2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment