[英]Using ggplot to plot points as lines with labels
我想在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等)的线。 请帮忙。
您需要geom_hline
并annotate
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)
我认为这是您想要的:
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))
我从reshape
使用melt()
将您的数据转换为长格式。 ggplot更喜欢这种格式。
然后创建一个ggplot,x轴为Year
,y轴为value
。 geom_line()
然后绘制穿过这些点的线。 geom_line()
需要分组变量来了解每个变量a,b,c...
是单独的行。
使用geom_line()
aes(color=variable)
根据变量variable
添加aes(color=variable)
。
请注意,如@tom所建议的那样,使用geom_hline()
可以更轻松地创建这种网格模式,但是这种方式更加灵活,可以制作非直线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.