Location letters in a horizontal line in R

Viewed 113

I have the following data

df<-read.table (text=" ID   Time
A   55
B   55
C   45
D   55
E   70
F   55
G   56
H   56
I   49
J   56
K   70
L   55
M   56
N   56
P   48
Q   55
R   63
S   55
T   49
U   45


", header=TRUE)

I want to plot the location of ID on a horizontal line. I want also to calculate the average time and show it in the line. This gives me a plot like this

enter image description here

1 Answers

Try this approach. You can smartly arrange your data, group by time and create a y coordinate based on row number. With that you can sketch the plot. The average line and its label can be added with annotate() and geom_vline(). Here the code using geom_text() and some tidyverse functions:

library(dplyr)
library(ggplot2)
#Plot
df %>%
  arrange(Time) %>%
  group_by(Time) %>%
  mutate(y=row_number()) %>%
  ggplot(aes(x=Time))+
  geom_text(aes(y=y,label=ID),size=3,fontface='bold')+
  geom_vline(data=df%>% summarise(Time=mean(Time)),aes(xintercept=Time),color='red')+
  theme_bw()+
  annotate(geom='text',
           x=df%>% summarise(Time=mean(Time)) %>% pull(Time)+3,
           label=paste0('Avg is ',df%>% summarise(Time=mean(Time)) %>% pull(Time)),
           y=7,fontface='bold',size=3)

Output:

enter image description here

And if you want to go around perfection in terms of customization:

#Plot 2
df %>%
  arrange(Time) %>%
  group_by(Time) %>%
  mutate(y=row_number()) %>%
  ggplot(aes(x=Time))+
  geom_text(aes(y=y,label=ID),size=3,fontface='bold')+
  geom_vline(data=df%>% summarise(Time=mean(Time)),aes(xintercept=Time),color='red')+
  theme_bw()+
  annotate(geom='text',
           x=df%>% summarise(Time=mean(Time)) %>% pull(Time)+3,
           label=paste0('Avg is ',df%>% summarise(Time=mean(Time)) %>% pull(Time)),
           y=7,fontface='bold',size=3)+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        panel.grid = element_blank())

Output:

enter image description here

To remove y-axis try this:

#Plot 3
df %>%
  arrange(Time) %>%
  group_by(Time) %>%
  mutate(y=row_number()) %>%
  ggplot(aes(x=Time))+
  geom_text(aes(y=y,label=ID),size=3,fontface='bold')+
  geom_vline(data=df%>% summarise(Time=mean(Time)),aes(xintercept=Time),color='red')+
  theme_bw()+
  annotate(geom='text',
           x=df%>% summarise(Time=mean(Time)) %>% pull(Time)+3,
           label=paste0('Avg is ',df%>% summarise(Time=mean(Time)) %>% pull(Time)),
           y=7,fontface='bold',size=3)+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        panel.grid = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank())+ylab('')

Output:

enter image description here

Related