Home > Software engineering >  how to put legend as a label in the middle of line in ggplot2
how to put legend as a label in the middle of line in ggplot2

Time:04-03

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

CodePudding user response:

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

CodePudding user response:

Not 100% what you desired. But one option would be the geomtextpath package which allows to easily add direct labels to lines or ...

library(ggplot2)
library(geomtextpath)

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

ggplot(data = df)  
  geom_textline(mapping = aes(y = direct, x = age, color = "direct", 
                              label = "direct"), linetype = "solid", offset = unit(5, "pt"), gap = FALSE)  
  geom_textline(mapping = aes(y = indirect, x = age, color = "indirect", 
                              label = "indirect"), linetype = "dashed", offset = unit(5, "pt"), gap = FALSE)  
  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))  
  guides(color = "none")

  • Related