重新排序同一地块上3个geom_smooth的图例标签

时间:2019-06-07 21:45:04

标签: r ggplot2 line legend

在过去的几个小时中,我一直在盯着解决方案,但是找不到类似的解决方案。我正在尝试使用3 geom_smooth来重新布置图例的图例标题。我的数据框有3列作为单独的行,并且它们都相对于第4列绘制。为了简化,我创建了一个非常小的数据框:

x <- data.frame("Score" = c(2,4,7,3,2,1,5,6,4,3,1,3), "var1" = c(3,4,3,6,7,6,4,3,5,7,7,3), "var2" = c(3,5,6,5,2,3,7,8,4,3,6,1))
x

ggplot(data = x)+
  geom_smooth(mapping = aes(x = Score, y=var1 , linetype = "var1"), color = "black", se = FALSE)+
  geom_smooth(mapping = aes(x = Score, y=var2, linetype = "var2"), colour = "black", se = FALSE)+
  scale_x_discrete()+
  scale_y_discrete()

在此示例中,我只想将“ 13-18岁时的y”移动到另一个标签下方。为了明确起见,此图上的两条线都在相同的比例(y)上。

非常感谢您的帮助!

编辑。

OP在comment中发布的新代码。

x <- data.frame("Score" = c(2,4,7,3,2,1,5,6,4,3,1,3), 
                "Age_6to10" = c(3,4,3,6,7,6,4,3,5,7,7,3), 
                "Age_13to18" = c(3,5,6,5,2,3,7,8,4,3,6,1))

x

ggplot(data = x) +
  geom_smooth(mapping = aes(x = Score, y= Age_6to10 , linetype = "y at Age 6-10"), color = "black", se = FALSE) +
  geom_smooth(mapping = aes(x = Score, y=Age_13to18, linetype = "y at Age 13-18"), colour = "black", se = FALSE)+ 
  scale_x_discrete() + 
  scale_y_discrete(name= "y") 

2 个答案:

答案 0 :(得分:1)

ggplot的最佳实践是重塑数据的形状,以便将要显示在图例中以及要映射到美学(例如线型)的每个特征放入一列中。在这种情况下,我使用ggplot(data = tidyr::gather(x, group, value, -Score)) + geom_smooth(mapping = aes(x = Score, y= value , linetype = forcats::fct_rev(group)), color = "black", se = FALSE) + scale_x_discrete() + scale_y_discrete(name= "y") + scale_linetype_discrete(name = "Age group") 将两个年龄组的值拉入一列,并将哪个年龄组的说明拉入另一列。

> tidyr::gather(x, group, value, -Score)
   Score      group value
1      2  Age_6to10     3
2      4  Age_6to10     4
3      7  Age_6to10     3
4      3  Age_6to10     6
5      2  Age_6to10     7
6      1  Age_6to10     6
7      5  Age_6to10     4
8      6  Age_6to10     3
9      4  Age_6to10     5
10     3  Age_6to10     7
11     1  Age_6to10     7
12     3  Age_6to10     3
13     2 Age_13to18     3
14     4 Age_13to18     5
15     7 Age_13to18     6
16     3 Age_13to18     5
17     2 Age_13to18     2
18     1 Age_13to18     3
19     5 Age_13to18     7
20     6 Age_13to18     8
21     4 Age_13to18     4
22     3 Age_13to18     3
23     1 Age_13to18     6
24     3 Age_13to18     1

enter image description here 重塑后的数据如下所示:

{{1}}

答案 1 :(得分:1)

最好将数据从宽到长重新格式化,然后再绘制。
标签按照请求的顺序排列,因为重新格式化variable是按正确顺序排列级别的一个因素。请参见下面的str的输出。

xlong <- reshape2::melt(x, id.vars = "Score")
str(xlong)
#'data.frame':  24 obs. of  3 variables:
# $ Score   : num  2 4 7 3 2 1 5 6 4 3 ...
# $ variable: Factor w/ 2 levels "Age_6to10","Age_13to18": 1 1 1 1 1 1 1 1 1 1 ...
# $ value   : num  3 4 3 6 7 6 4 3 5 7 ...


ggplot(data = xlong,
       mapping = aes(x = Score, y = value, linetype = variable)) +
  geom_smooth(color = "black", se = FALSE) +
  scale_x_discrete() + 
  scale_y_discrete(name= "y") 

enter image description here