繁体   English   中英

如何将图例作为 label 放在 ggplot2 的行中间

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

这是我的图表线数据和代码:

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))


我想将图例放在每一行的中间,如图所示:

在此处输入图像描述

您可以在行中添加annotate 您可以使用以下代码:

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:

在此处输入图像描述

不是您想要的 100%。 但一种选择是geomtextpath package,它允许轻松地将直接标签添加到行或...

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM