0

I am labeling points in a regression and want to "mask" the labels so they are easy to read when they intersect the line. ArcGIS has a function for this called masking. Simple masking is essentially adding a white background (or shadow/mask) to text. I have looked over the ggplot text documentation and it seems the ggplot way of fixing this would be to use geom_label, but I find that a bit clunky looking. I am trying to make the area I highlighted with red pen on

this figure

look a bit nicer.
Sample:

ggplot(mtcars[1:10,], aes(wt, mpg)) +
  geom_point() +
  stat_smooth(method="lm", se=FALSE, color="black") +
  geom_text(aes(label=rownames(mtcars)[1:10]),hjust=.5, vjust=-.4)#mask text? 

Solution:

ggplot(mtcars[1:10,], aes(wt, mpg)) +
  geom_point() +
  stat_smooth(method="lm", se=FALSE, color="black") +
  geom_shadowtext(aes(label=rownames(mtcars)[1:10]),hjust=.5, vjust=-.4,
                  col="black", bg.color="white", cex=4, r=2) 
DylanMG
  • 45
  • 6
  • 1
    Have you looked into the `ggrepel` package? – Ian Campbell Mar 26 '20 at 22:19
  • It would be nice if you could give the sample data and code to generate this plot. Thanks. – r2evans Mar 26 '20 at 22:39
  • @r2evans something like this: ggplot(mtcars, aes(wt, mpg)) + geom_point() + stat_smooth(method="lm", se=FALSE, color="black") + geom_text(aes(label=rownames(mtcars)),hjust=.5, vjust=-.4) #mask text? – DylanMG Mar 26 '20 at 23:01
  • @S.Confluentus: try `shadowtext` package? https://stackoverflow.com/a/52808472/786542 – Tung Mar 26 '20 at 23:01
  • `m <- mtcars[1:10, ]; ggplot(m, aes(mpg, disp)) + stat_smooth(method = 'lm', se = FALSE) + theme_classic() + geom_label(aes(label = rownames(m)), nudge_y = 10, label.size = NA) + geom_point()` – rawr Mar 26 '20 at 23:02
  • Code and data don't always show well in comments, and comments can be skipped by readers or hidden by the SE interface. Would you please [edit] your question and add that code (and sample data)? – r2evans Mar 26 '20 at 23:02
  • @rawr I thought of this but was hoping there was a nice way for the line to kind of pass through a label like the "Merc 230" label by getting a little closer to it. – DylanMG Mar 26 '20 at 23:05

0 Answers0