2015-12-25 13 views
3

聖誕祝福!請,使用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 
+0

添加一個可重現的示例...我們無法訪問您的數據集,因此我們無法測試您的代碼。 – MLavoie

回答

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

完成

更新:

取得了較好的數據,並添加變量,名稱更靈活地指示c olor和線型。

+1

...非常感謝您的幫助。在這個吉祥的日子,上帝保佑你。 :) –

相關問題