I want to add country labels (actually ten) to a rworldmap
. Two of them overlap because they're small, bordering states. I want to move one of them a little to the side, but keep the first one in place.
I think I don't need to show the rworldmap
code here since I could break down the issue to the text
function.
From the function's arguments defaults
text(x, y = NULL, labels = seq_along(x$x), adj = NULL,
pos = NULL, offset = 0.5, vfont = NULL,
cex = 1, col = NULL, font = NULL, ...)
I would conclude that the default pos
is NULL
, so I say pos=c(NULL, 4)
. However this doesn't work as expected; the first label is also moved. The moveString
is moved correctly, but the other should stay where it is. I have tried all available pos
for the stayString
, but they do not correspond to the original position. I also tried adj
with no success.
plot(0:3, type="n")
grid()
text(c(2, 2.2), rep(3, 2), c("stayString", "moveString"),
col="black") # raw
text(c(2, 2.2), rep(2.5, 2), c("stayString", "moveString"),
pos=c(NULL, 4), col="red") # unexpected result
# other attempts
text(c(2, 2.2), rep(2, 2), c("stayString", "moveString"),
pos=c(1, 4), col="green")
text(c(2, 2.2), rep(1.5, 2), c("stayString", "moveString"),
adj=c(.5, 1), col="blue")
text(c(2, 2.2), rep(1, 2), c("stayString", "moveString"),
pos=c(2, 4), col="purple")
text(c(2, 2.2), rep(.5, 2), c("stayString", "moveString"),
pos=c(1, 4), adj=c(.5, 1), col="orange")
I am rather looking for such an adjustment solution because I don't like to change the coordinates since they nicely represent the center of each country.
How can I move the moveString
and keep the stayString
in position without changing the x
/y
coordinates?
A solution that comes to mind is to create two functions, and split each string based on the fact that you want to offset
it or not.
We can use, from text()
, pos
and offset
to move the text a little.
text_stay <- function(x, y, lab, ...) {
text(x,y, labels=lab, ...)
}
text_move <- function(x,y,lab, p=4, off=2, ...) {
text(x, y, labels=lab, pos=p, offset=off, ...)
}
So for example:
plot(0:3, type="n")
grid()
# split the text and use the appropriate wrapper function
text_stay(rep(2, 3), 1:3, "stay", col="red")
text_move(rep(2, 3), 1:3, "move", col = "blue")