Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to put legend as a label in the middle of line in ggplot2

here is my data and code for chart line:

df<- data.frame(direct= 10:85, indirect= 55:130, age=15:90)

ggplot(data=df)+
  geom_line(mapping=aes(y=direct,x= age,color="direct"),linetype="solid" ) +
  geom_line(mapping=aes(y=indirect,x= age,color="indirect"),linetype="dashed") +
  scale_color_manual(values = c(
    'direct' = 'black',
    'indirect' = 'black')) +
  labs(color = NULL)+
  scale_x_continuous(breaks = seq(15, 90, by = 5))+ 
  labs(y= "Time Spent (in minutes)")+
  guides(color = guide_legend(override.aes = list(linetype = c("solid","dashed"))))+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5, size=9, face="bold"),legend.position=c(.90,.90))


I want to put legend in the middle of my each line as the picture:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add annotate to your lines. You can use the following code:

library(tidyverse)
df<- data.frame(direct= 10:85, indirect= 55:130, age=15:90)

ggplot(data=df)+
  geom_line(mapping=aes(y=direct,x= age,color="direct"),linetype="dashed" ) +
  geom_line(mapping=aes(y=indirect,x= age,color="indirect"),linetype="solid") +
  scale_color_manual(values = c(
    'direct' = 'black',
    'indirect' = 'black')) +
  labs(color = NULL)+
  scale_x_continuous(breaks = seq(15, 90, by = 5))+ 
  labs(y= "Time Spent (in minutes)")+
  guides(color = guide_legend(override.aes = list(linetype = c("solid","dashed"))))+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5, size=9, face="bold"), legend.position = "none") +
  annotate('text', x=50, y=55, label = "direct")+
  annotate('text', x=50, y=100, label = "indirect") 

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading