简体   繁体   中英

Fit entire text into a plot area

I want to create a plot with text but it seems that ggplot ignores text when identifying x and y limits (it uses only centerpoint). So if the text too long it is not fully visible.

df <- tibble(x = 1:5, y = 1:5)
ggplot(df, aes(x, y, label = paste(rep("long text", 3), collapse = " "))) +
  geom_point() + geom_text(nudge_y = 0.2)

在此处输入图像描述

In this case one can add layer expand_limits(x = c(0.4, 5.6)) but that doesn't work for any other case. I would like to have something that works for any values of x and y and any length of text.

You can use ggrepel for this:

library(ggrepel)

ggplot(df, aes(x, y, label = paste(rep("long text", 3), collapse = " "))) +
  geom_point() + ggrepel::geom_text_repel(nudge_y = 0.2, segment.alpha = 0)

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM