我想在我的情节左上角添加我的两个数据集的传说,但是我从其他脚本中获取的代码不起作用,没有人有任何人想法为什么?
library("ggplot2")
library("reshape2")
data<-read.csv("trial.csv",header=TRUE,dec=".",sep=',',na.strings="NA")
#Example of data
Year Annual Cumulative
1 1960 1 1
2 1961 0 1
3 1962 0 1
4 1963 0 1
5 1964 0 1
6 1965 0 1
7 1966 0 1
8 1967 1 2
9 1968 0 2
10 1969 0 2
11 1970 0 2
12 1971 0 2
13 1972 1 3
14 1973 0 3
15 1974 1 4
16 1975 1 5
17 1976 0 5
18 1977 0 5
19 1978 0 5
20 1979 4 9
21 1980 2 11
22 1981 1 12
23 1982 1 13
24 1983 3 16
25 1984 1 17
26 1985 2 19
27 1986 1 20
28 1987 4 24
29 1988 3 27
30 1989 3 30
31 1990 3 33
32 1991 1 34
33 1992 4 38
34 1993 0 38
35 1994 4 42
36 1995 4 46
37 1996 3 49
38 1997 5 54
39 1998 2 56
40 1999 0 56
41 2000 6 62
42 2001 11 73
43 2002 8 81
44 2003 2 83
45 2004 5 88
46 2005 7 95
47 2006 13 108
48 2007 22 130
49 2008 13 143
50 2009 13 156
51 2010 17 173
52 2011 14 187
53 2012 24 211
54 2013 24 235
55 2014 18 253
56 2015 19 272
57 2016 17 289
58 2017 16 305
59 2018 24 329
60 2019 9 338
绘制代码:
p1<-ggplot(data=data,aes(x=Year))+
geom_line(aes(y=Cumulative),linetype="solid",color="red",size=1.1)+
geom_point(aes(y=Cumulative),shape=1,color="red",size=3,stroke=1.5)+
geom_line(aes(y=Annual),linetype="solid",color="darkorange",size=1.1)+
geom_point(aes(y=Annual),shape=1,color="darkorange",size=3,stroke=1.5)+
scale_y_continuous(sec.axis=sec_axis(~.*1/10,name="Annualn"))
p1<-p1+labs(x="nYear",y="Cumulativen")
p1+theme(axis.title.x=element_text(size=18),
axis.text.x=element_text(size=14),
axis.title.y=element_text(size=18),
axis.text.y=element_text(size=14),
axis.ticks=element_blank())
有多种替代方法可以做到这一点。一件快速的事情是按年份融化数据,并简化GEOM_POINT和GEOM_LINE以删除重复。您将为您创建一个传说,您可以根据传奇来自定义和重新定位。
中的位置。library("ggplot2")
library("reshape2")
data.melt <- melt(data, "Year")
ggplot(data.melt, aes(x = Year, y = value, color = variable)) +
geom_point(shape=1, size=3, stroke=1.5) +
geom_line(linetype="solid", size=1.1) +
scale_colour_manual(values=c("darkorange", "red")) +
scale_y_continuous(sec.axis=sec_axis(~.*1/10, name="Annualn")) +
labs(x="nYear", y="Cumulativen", color="Legend Title") +
theme(axis.title.x=element_text(size=18),
axis.text.x=element_text(size=14),
axis.title.y=element_text(size=18),
axis.text.y=element_text(size=14),
axis.ticks=element_blank(),
legend.position = c(0.1, 0.9))