Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text to ggplot

Tags:

r

label

ggplot2

(updated) I have ggplot like this, but then the x axis Date scaled:

g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() 

Above two bars (lets say VS2 and IF, but in my graph it is a date) I want to put a text label above the bars at height 13.000.

I tried a lot of things, but this is what came closest: This is what I tried in my graph with the Date axis g1 + geom_text(aes(as.Date("2014-10-05"), 13000), label="boat")

but this adds only one to the graph and as soon as I try to extend it, for example with

g1 + geom_text(aes(c(as.Date("2014-10-05"),as.Date("2014-10-20")) , 13000), label=c("boat", "train")) 

then I get the error:

Error: Aesthetics must either be length one, or the same length as the dataProblems:c(as.Date("2014-10-05"), as.Date("2014-10-20"))

I also tried to read the text and labels from a dataframe (oefen), where I used the same names as the original plot

g1 + geom_text(data=oefen, aes(x=newdat, y=Number, label=oefen$labs, fill=1)) 

I get the error

Error: Continuous value supplied to discrete scale

I tried many other solutions, but cannot find the answer. What am I missing?

like image 643
Rosanne Avatar asked Feb 27 '15 00:02

Rosanne


People also ask

How do I add labels in Ggplot?

To add labels at specified points use annotate() with annotate(geom = "text", ...) or annotate(geom = "label", ...) . To automatically position non-overlapping text labels see the ggrepel package.

How do I annotate a plot in R?

If you want to annotate your plot or figure with labels, there are two basic options: text() will allow you to add labels to the plot region, and mtext() will allow you to add labels to the margins. For the plot region, to add labels you need to specify the coordinates and the label.


1 Answers

Consider using annotate() to place whatever text where you want at a given location on the plot. Factor variables, as in the clarity factor on the x-axis, have a number for each level, so you can use that number to locate the text. I assume date variables have the same usage.:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +   annotate("text", x=8, y=13000, label= "boat") +    annotate("text", x = 4, y=13000, label = "ship") 

enter image description here

EDIT after COMMENT

For efficiency, you can combine the annotations, such as this:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +   annotate("text", x = c(2,4,6,8), y=13000, label = c("two", "ship", "six", "boat")) 
like image 76
lawyeR Avatar answered Sep 22 '22 12:09

lawyeR