KevinP
KevinP

Reputation: 11

ggplot: Adding labels to lines, not endpoints

Looking for some gglot help here, for a pretty non-standard plot type. Here is code for one sample graph, but the final product will have dozens like this.

library(ggplot2)
library(data.table)

SOURCE <- c('SOURCE.1','SOURCE.1','SOURCE.2','SOURCE.2')
USAGE <- rep(c('USAGE.1','USAGE.2'),2)
RATIO <- c(0.95,0.05,0.75,0.25)
x <- data.table(SOURCE,USAGE,RATIO)

ggplot(x, aes(x=SOURCE,y=RATIO,group=USAGE)) +
    geom_point() +
    geom_line() +
    geom_label(aes(label=USAGE))

This produces a graph with two lines, as desired. But the label geom adds text to the endpoints. What we want is the text to label the line (appearing once per line, around the middle). The endpoints will always have the same labels so it just creates redundancy and clutter (each graph will have different labels). See the attached file, mocked up in a paint programme (ignore the font and size):

mock up

I know we could use geom_line(aes(linetype=USAGE)), but we prefer not to rely on legends due to the sheer number of graphs required and because each graph is quite minimal as the vast majority will have just the two lines and the most extreme cases will only have four.

(Use of stacked bars deliberately avoided.)

Upvotes: 1

Views: 3752

Answers (1)

MarBlo
MarBlo

Reputation: 4524

You can achieve this with annotate and can move the label around by changing the x and y values.

library(ggplot2)
#library(data.table)

SOURCE<-c('SOURCE.1','SOURCE.1','SOURCE.2','SOURCE.2')
USAGE<-rep(c('USAGE.1','USAGE.2'),2)
RATIO<-c(0.95,0.05,0.75,0.25)
#x<-data.table(SOURCE,USAGE,RATIO)

df <- data.frame(SOURCE, USAGE, RATIO)

ggplot(df, aes(x=SOURCE,y=RATIO,group=USAGE)) +
  geom_point() +
  geom_line() +
  #geom_label(aes(label=USAGE))+
  annotate('text', x=1.5, y=1, label = USAGE[1])+
  annotate('text', x=1.5, y=0.25, label = USAGE[2])

Upvotes: 1

Related Questions