顶部位置的图例未显示

时间:2015-12-25 13:48:12

标签: r graph ggplot2 legend

圣诞节问候!请使用R来帮助我们根据线型绘制图例:

ggplot(mkt_liq, aes(x = Timestamp)) + geom_line(aes(y = CG), colour="green",linetype = "solid",size=1,alpha = 1,show_guide = TRUE) +  
geom_line(aes(y = FS), colour = "red",linetype = "dotdash",size=1,show_guide = TRUE) +   geom_line(aes(y = MAN), colour = "black",linetype = "dotted",size=1,show_guide = TRUE)+   
geom_line(aes(y = INFRA), colour = "blue",linetype = "longdash",size=1,show_guide = TRUE)+ ylab(label="Sectors") +   xlab("Time")+ theme(legend.position="top")

数据集如下:

Timestamp   CG          FS            MAN        INFRA
9:30:00     0.680211107 0.11651278  4.792954196 0.643453697
10:00:00    0.486717157 0.106090614 2.996018087 0.387472797
10:30:00    0.458210851 0.103258739 2.802459194 0.360074724
11:00:00    0.450227036 0.103551557 2.706885909 0.365001632

1 个答案:

答案 0 :(得分:4)

您需要使用重塑并融化变量:

library(ggplot2)
library(reshape2)

set.seed(1234)
n <- 100
sdate <- as.POSIXct("2015-11-11 00:00:00",tz="UCT")
edate <- as.POSIXct("2015-11-11 23:59:59",tz="UCT")

mkt_liq <- data.frame(
  Timestamp =  as.POSIXct(runif(n,sdate,edate),tz="UCT",origin="1970-01-01"),
  CG = 0.5 + rnorm(n,0,0.15),
  FS = 0.1 + rnorm(n,0,0.01),
  MAN = 2.8 + rnorm(n,0,0.5),
  INFRA = 0.4 + rnorm(n,0,0.05)
)

# The wrong way
ggplot(mkt_liq, aes(x = Timestamp)) + 
  geom_line(aes(y = CG), colour="green",linetype = "solid",size=1) +  
  geom_line(aes(y = FS), colour = "red",linetype = "dotdash",size=1) +   
  geom_line(aes(y = MAN), colour = "black",linetype = "dotted",size=1)+   
  geom_line(aes(y = INFRA), colour = "blue",linetype = "longdash",size=1)+ 
  ylab(label="Sectors") +   
  xlab("Time")+ 
  theme(legend.position="top")

产生这个:

enter image description here

但你真正想要的是:

# The right way
mdf <- melt(mkt_liq,id=c("Timestamp"),variable.name="Sector" )

clrs <- c("CG"="green","FS"="red","MAN"="black","INFRA"="blue")
ltyp <- c("CG"="solid","FS"="dotdash","MAN"="dotted","INFRA"="longdash")

ggplot(mdf, aes(x = Timestamp,y=value,color=Sector,linetype=Sector)) + 
  geom_line(size=1)+
  ylab(label="Sectors") +   
  xlab("Time")+ 
  scale_color_manual( values=clrs )+
  scale_linetype_manual( values=ltyp )+
  theme(legend.position="top")

得出这个: enter image description here

完成

更新

制作更好的数据并添加变量和名称,以更灵活地指示颜色和线型。