使用ggplot将点绘制为带有标签的线

时间:2019-08-07 12:05:19

标签: r ggplot2

我想在ggplot中将点绘制为水平线,并在每条线的末尾添加标签。参考点是:

Year          a           b          c           d           e          f      g      h
2014 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
2015 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
2016 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
2017 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
2018 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333

我需要在y轴上绘制a,b,c,d,e,f,g和h,在x轴上绘制YEAR,以线的形式分别绘制颜色,并以a,b,c,d等标记。请帮忙。

2 个答案:

答案 0 :(得分:1)

您需要geom_hlineannotate

  ggplot(mtcars, aes(cyl, wt)) + 
    geom_point(alpha = 0.4) +
    geom_hline(yintercept = a) + 
    geom_hline(yintercept = b) + 
    geom_hline(yintercept = c) + 
    annotate(geom="text", label="a", x=max(mtcars$cyl)+1, y=a, vjust=-1) + 
    annotate(geom="text", label="b", x=max(mtcars$cyl)+1, y=b, vjust=-1) + 
    annotate(geom="text", label="c", x=max(mtcars$cyl)+1, y=c, vjust=-1) 

答案 1 :(得分:1)

替换了先前的答案

我想这就是你想要的:

df <- read.csv(text = "Year a b c d e f g h
 2014 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
 2015 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
 2016 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
 2017 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333
 2018 0.02932623 0.006530686 0.05212177 0.007424746 0.004063887 0.01078561 0.0101 0.0333", sep=' ',header=T)


 library(ggplot2)
 library(reshape2)

 df_melt <- melt(data=df, id.vars='Year')

 ggplot(data=df_melt, aes(x=Year,y=value, group=variable)) +
  geom_line(aes(color=variable))

我使用melt()中的reshape将您的数据转换为长格式。 ggplot更喜欢这种格式。
然后,我创建了一个ggplot,其x轴为Year,y轴为valuegeom_line()然后绘制穿过这些点的线。 geom_line()需要分组变量来了解每个变量a,b,c...是单独的行。
使用variable中的aes(color=variable),根据变量geom_line()添加颜色。

请注意,使用geom_hline()可以更方便地制作这种类型的网格图案,如@tom所建议的那样,但是这种方式更加灵活,可以制作非直线。