Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text labels to ggplot2 scatterplot

Is there a good way easy way to add text labels to the circles on the graph? I haven't able to do it using the directlabels package because I get the error:

Error in direct.label.ggplot(p, "first.qp") : Need colour aesthetic to infer default direct labels."

Here is the graph: What I have at the moment

And here is the code that I've been using:

library(ggplot2)
library(directlabels)
#my data set:
oc <- read.csv("http://www.columbia.edu/~mad2200/oc.csv")
oc$percent_women <- oc$W_employment/(oc$M_employment+oc$W_employment)
oc$size <- oc$W_employment+oc$M_employment
p <- ggplot(oc, aes(M_w_earnings, W_w_earnings, label = as.character(Occupational.Group)))
p + geom_point(aes(size = size, colour=percent_women)) + scale_size_continuous(range=c(0,30)) + #scale_area()+
#geom_point(aes(colour = oc$percent_women)) + 
coord_equal() +
scale_colour_gradient(high = "red")+
ylim(700, 1700) +
xlim(700, 1700) +
geom_abline(slope=1) +
labs(title = "Income Disparity by Occupation and Gender") +
ylab("Women's Weekly Earnings in $") +
xlab("Men's Weekly Earnings in $")
like image 898
Michael Discenza Avatar asked Oct 23 '12 03:10

Michael Discenza


People also ask

How do you add data labels to a scatter plot in R?

To add the labels, we have text() , the first argument gives the X value of each point, the second argument the Y value (so R knows where to place the text) and the third argument is the corresponding label. The argument pos=1 is there to tell R to draw the label underneath the point; with pos=2 (etc.)

How do I add text to a scatterplot in R?

To add a text to a plot in R, the text() and mtext() R functions can be used.

How do I add text to ggplot2?

You can use the annotate() function to add text to plots in ggplot2. where: x, y: The (x, y) coordinates where the text should be placed. label: The text to display.

How do you add data point labels to ggplot?

To put labels directly in the ggplot2 plot we add data related to the label in the data frame. Then we use functions geom_text() or geom_label() to create label beside every data point. Both the functions work the same with the only difference being in appearance.


1 Answers

Add geom_text(aes(label=Occupational.Group), size=3) to the plot. You'll need to play with the size though.

enter image description here

like image 103
Jared Avatar answered Sep 19 '22 13:09

Jared