37

The text printed using geom_text is not very clear. How can I make it more clear?

data = data.frame(rnorm(1000))
colnames(data) = "numOfX"
m <- ggplot(data, aes(x=numOfX))
m + geom_histogram(colour = "blue", fill = "white", binwidth = 0.5) +
  annotate("segment", x=10,xend=10,y=20,yend=0,arrow=arrow(), color="blue") +
  geom_text(aes(10, 30, label="Observed \n value"), color = "blue") 

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
learner
  • 2,582
  • 9
  • 43
  • 54
  • possible duplicate of [ggplot2: Is there a fix for jagged, poor-quality text produced by geom_text()?](http://stackoverflow.com/questions/10952832/ggplot2-is-there-a-fix-for-jagged-poor-quality-text-produced-by-geom-text) – Ari B. Friedman Jul 23 '12 at 20:17
  • 4
    An easy fix for this is to use the argument `check_overlap = TRUE` within `geom_text` – Dave Gruenewald Oct 03 '17 at 18:10

2 Answers2

51

Use annotate for the text as well as the arrow:

m + geom_histogram(colour = "blue", fill = "white", binwidth = 0.5) +
  annotate("segment", x=10,xend=10,y=20,yend=0,arrow=arrow(), color="blue") +
  annotate("text", x=10, y=30, label="Observed \n value", color = "blue")

enter image description here


The reason is that geom_text overplots the text for each row of data in the data frame, whereas annotate plots the text only once. It is this overplotting that causes the bold, pixellated text.

I am sure this question was answered recently. I'll try to find a reference: A similar question was asked recently:

Community
  • 1
  • 1
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • So in the case, we use a vector of labels in different positions we should use `geom_text` and this will not have the blurry effect it has with only one label, right? – Garini Nov 15 '18 at 13:09
  • 2
    It's odd that overplotting with exact coordinates should lead to fuziness though – duhaime Apr 14 '19 at 11:32
6

Expanding on Dave Gruenewald's comment, geom_text now has the check_overlap option. See the tidyverse reference:

check_overlap -- If TRUE, text that overlaps previous text in the same layer will not be plotted. check_overlap happens at draw time and in the order of the data. Therefore data should be arranged by the label column before calling geom_text(). Note that this argument is not supported by geom_label().

library(ggplot2)
data = data.frame(rnorm(1000))
colnames(data) = "numOfX"
m <- ggplot(data, aes(x=numOfX))
m + geom_histogram(colour = "blue",
                   fill = "white",
                   binwidth = 0.5) +
  annotate("segment",
           x = 10, xend = 10,
           y = 20, yend = 0,
           arrow = arrow(), color="blue") +
  geom_text(aes(10, 30, label="Observed \n value"),
            color = "blue", check_overlap = T)

enter image description here

acvill
  • 395
  • 7
  • 15