我想同时为两个geom_line
和一个geom_point
添加图例,但传说并不是彼此对齐的。那么如何调整两个图例并调整图例位置呢?提前谢谢!
我的数据:
DF1:
x1 y1
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 9.2
24 18.5
25 27.6
26 36.8
27 46.1
28 54.2
29 63.4
30 72.6
31 81.7
32 88.9
33 93
34 99.1
35 105.4
36 110
37 118.3
38 128.2
39 138
40 146.9
41 155.1
42 162.5
43 165.7
44 169.2
45 174.2
46 176.3
47 183.8
48 187.8
49 194.2
50 200.7
51 203.4
52 204.7
53 209.5
54 214.5
55 219.6
56 224.1
57 228.5
58 232.8
59 237
60 239.5
61 242.7
62 243.1
63 244.6
64 245
65 246.6
66 248.6
67 251
68 253
69 255
70 256.7
71 256.7
DF2:
x2 y2
24 0.006525
32 0.072525
39 0.120025
46 0.1601418
53 0.1972939
60 0.2226233
68 0.2312895
DF3:
x3 y3
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 10.9
24 14.8
25 19.6
26 25.6
27 31.4
28 38.5
29 47.1
30 56.9
31 64.7
32 71
33 77
34 84.7
35 92.5
36 98.8
37 108.2
38 118.8
39 126.9
40 134.3
41 141.1
42 147.2
43 149.9
44 152.8
45 157
46 158.7
47 164.9
48 168.3
49 173.6
50 179
51 181.3
52 182.3
53 186.3
54 190.4
55 194.7
56 198.5
57 202.1
58 205.7
59 209.2
60 211.3
61 213.9
62 214.3
63 215.6
64 215.9
65 217.2
66 218.9
67 220.9
68 222.5
69 224.2
70 225.7
71 225.7
我的代码:
library("ggplot2")
library("reshape2")
library("gridExtra")
p <- ggplot() +
geom_line(data=df1, aes(x= x1, y= y1, linetype= "aa"))+
geom_point(data=df2, aes(x= x2, y= y2, shape="bbbbbbb"))+
geom_line(data=df3, aes(x= x3, y= y3, linetype= "cc"))+
scale_shape_manual(name="",
labels=c("bbbbbbb"),
values = c(21) )+
scale_linetype_manual(name="",
labels=c("aa","cc"),
values=c("solid", "dashed")) +
ylab("y")+
xlab("x")+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.justification = c(0, 1),
legend.position=c(0, 1))
我的情节:
答案 0 :(得分:1)
谢谢你们的关注。我找到了问题的解决方案,我从this post采纳了这个想法。
library("ggplot2")
library("reshape2")
library("gridExtra")
library("gtable")
p <- ggplot() +
geom_line(data=df1, aes(x= x1, y= y1, linetype= "aa"))+
geom_point(data=df2, aes(x= x2, y= y2, shape="bbbbbbb"))+
geom_line(data=df3, aes(x= x3, y= y3, linetype= "cc"))+
# discard errorbar here.
scale_shape_manual(name=NULL,
labels=c("bbbbbbb"),
values = c(21) )+
scale_linetype_manual(name=NULL,
labels=c("aa","cc"),
values=c("solid", "dashed")) +
ylab("y")+
xlab("x")+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position=c(0, 1),
legend.justification=c(0,1),
legend.margin=unit(0,"cm"),
legend.box="vertical",
legend.box.just = "left",
legend.key.size=unit(1,"lines"),
legend.text.align=0,
legend.key = element_blank(),
legend.title = element_blank(),
legend.background=element_blank())
data <- ggplot_build(p)
gtable <- ggplot_gtable(data)
lbox <- which(sapply(gtable$grobs, paste) == "gtable[guide-box]")
guide <- gtable$grobs[[lbox]]
gtable$grobs[[lbox]]$heights <- unit.c(guide$heights[1:2],
unit(-.8,"cm"),
guide$heights[2:3])
# Plotting
g<-grid.draw(gtable)