ggplot折线图中的可变标签位置 [英] Variable label position in ggplot line chart

查看:184
本文介绍了ggplot折线图中的可变标签位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用dplyr

structure(list(maxrep = c(7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L, 11L, 
11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L, 17L, 17L, 
18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L, 23L, 24L, 
24L, 26L, 26L), div = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("Premier Division", 
"Second Division"), class = "factor"), freq = c(1L, 10L, 4L, 
39L, 26L, 89L, 73L, 146L, 107L, 162L, 117L, 133L, 121L, 125L, 
116L, 91L, 110L, 65L, 95L, 43L, 75L, 38L, 43L, 24L, 38L, 16L, 
36L, 5L, 15L, 2L, 9L, 7L, 9L, 1L, 3L, 3L, 2L, 1L)), .Names = c("maxrep", 
"div", "freq"), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -38L))

我的目的是使用ggplot2绘制具有不同颜色的2条线的折线图,并为每个值添加文本标签.

My intention is to use ggplot2 to plot line graphs of 2 lines with different colour with text labels for each value.

我所做的是

ggplot(df, aes(x=maxrep, y=freq, colour=div)) +
geom_line() +
geom_text(aes(label=freq), vjust=-.5)

结果是

现在是我的问题:图表中的所有标签均位于相应线条中的点上方.我想让不同颜色的标签位于不同的相对位置,例如该行上方为青色的标签,该行下方为红色的标签(即变量vjust).有办法吗?

Now my question: All the labels in the chart are above the points in respective lines. I want to have the labels for the different colours to be in different relative position, e.g. labels for cyan above the line, and labels for red below the line (i.e. variable vjust). Is there a way to do that?

还可以读取右侧颜色图例中的字母a吗?

Also, is there a way to get read of the letter a in the colour legend on the right?

推荐答案

在包含vjust调整参数的data.frame中创建一个新变量:

Create a new variable in the data.frame holding the vjust adjustment parameter:

df$pos <- c(2, -2)[(df$div == "Premier Division")+1] 

您可以使用新的pos向量在aes内部调用vjust:

And you could call vjust inside aes with the new pos vector:

ggplot(df, aes(x=maxrep, y=freq, colour=div)) +
    geom_line() +
    geom_text(aes(label=freq, vjust=pos))

这篇关于ggplot折线图中的可变标签位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆