Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbered point labels plus a legend in a scatterplot

Tags:

r

ggplot2

I am trying to label points in a scatterplot in R (ggplot2) using numbers (1, 2, 3, ...) and then match the numbers to names in a legend (1 - Alpha, 2 - Bravo, 3 - Charlie... ), as a way of dealing with too many, too long labels on the plot.

Let's assume this is a.df:

Name      X Attribute   Y Attribute  Size Attribute  Color Attribute
Alpha     1             2.5          10              A
Bravo     3             3.5          5               B
Charlie   2             1.5          10              C
Delta     5             1            15              D

And this is a standard scatterplot:

ggplot(a.df, aes(x=X.Attribute, y=Y.Attribute, size=Size.Attribute, fill=Colour.Attribute, label=Name)) +
   geom_point(shape=21) +
   geom_text(size=5, hjust=-0.2,vjust=0.2)

Is there a way to change it as follows?

  • have scatterplot points labeled with numbers (1,2,3...)
  • have a legend next to the plot assigning the plot labels (1,2,3...) to a.df$Name

In the next step I would like to assign other attributes to the point size and color, which may rule out some 'hacks'.

like image 891
Radoslav Avatar asked May 13 '26 02:05

Radoslav


1 Answers

Here's an alternative solution, which draws the labels as geom_text. I've borrowed from ggplot2 - annotate outside of plot.

library(MASS)  # for Cars93 data
library(grid)
library(ggplot2)

d <- Cars93[1:30,]
d$row_num <- 1:nrow(d)
d$legend_entry <- paste("  ", d$row_num, d$Manufacturer, d$Model)

ymin <- min(d$Price)
ymax <- max(d$Price)
y_values <- ymax-(ymax-ymin)*(1:nrow(d))/nrow(d)

p <- ggplot(d, aes(x=Min.Price, y=Price)) +
        geom_text(aes(label=row_num)) +
        geom_text(aes(label=legend_entry, x=Inf, y=y_values, hjust=0)) +
        theme(plot.margin = unit(c(1,15,1,1), "lines"))

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

R plot

like image 71
James Trimble Avatar answered May 15 '26 18:05

James Trimble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!