I'm trying to add labels to segments I created in a graph using ggplot
dat <- data.frame(start <- c(-1.05113647, -0.63911585, -0.62791554),
end <- c(0.37491159, -0.13911585, -0.12791554),
order <- c("Sei whale", "Probeagle", "Northern fur seal"),
pos <- c(1, 2, 3))
ggplot(dat) +
geom_segment(aes(x=start, y=start, xend=end, yend=start), colour = "blue", size = 2) +
scale_y_reverse() +
xlab("PC1")+
ylab(" ")+
theme_linedraw() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank()) +
theme(aspect.ratio = 0.3) +
theme(legend.position="none") +
theme(axis.ticks = element_blank(), axis.text.y = element_blank())
I'd like to know how to add the names from the "order" to their respective segments.
You can use geom_text()
:
library(ggplot2)
ggplot(dat) +
geom_segment(aes(start, start, xend = end, yend = start),
colour = "blue",
size=4) +
geom_text(aes((end + start) / 2,
y = start,
label = order),
color = 'grey75',
size = 3,
nudge_y = .005) +
scale_y_reverse() +
xlab("PC1")+
ylab(" ")+
theme_linedraw() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
aspect.ratio = 0.3,
legend.position="none",
axis.ticks = element_blank(),
axis.text.y = element_blank())
The result is not particularly pretty imo, I increased the segment
size
, to let the text be visible.
You could try geom_dl()
from the directlabels
package and expand the x axis a bit:
library(ggplot2)
library(directlabels)
ggplot(dat) +
geom_segment(aes(x = start, y = start, xend = end, yend = start),
colour = "blue", size = 2) +
scale_y_reverse() +
geom_dl(aes(end, start, label = order),
method = list(dl.trans(x = x + 0.2), "last.bumpup", cex = 0.60)) +
scale_x_continuous(expand = c(0, 0.2)) +
labs(x = "PC1", y = " ") +
theme_linedraw() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank()) +
theme(aspect.ratio = 0.7) +
theme(legend.position = "none") +
theme(axis.ticks = element_blank(), axis.text.y = element_blank())
Which gives:
Note : I changed the aspect.ratio
to 0.7 to make it more readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.