2014-10-17 98 views
0

我想更改圖例中的標籤。ggplot2更改圖例中的標籤

spi<-read.csv("spill.csv",as.is=TRUE) 
attach(spi) 
spi$date<-as.Date(spi$date) 
str(spi) 
data.frame: 3184 obs. of 3 variables: 
$ data1: chr "oil to asset" "oil to asset" "oil to asset" "oil to asset" ... 
$ date : Date, format: "2007-01-10" "2007-01-11" ... 
$ sp : num 7.7 7.95 7.54 7.61 7.67 ... 

cont1 <- ggplot(spi,aes(x=date,y=sp,linetype=data1))+geom_line() + 
      expand_limits(max(spi$sp), y=c(0,80)) + 
      labs(x = "", y = "") + 
      scale_y_continuous(breaks=seq(0,80,10)) + 
      scale_linetype_manual(values = c("dashed","solid")) + 
      scale_x_date(breaks=datebreaks1, labels=date_format("%Y")) + 
      ggtitle("Oil and Fianacial Market") + 
      annotate("rect", xmin=as.Date("2008-01-02"), xmax=as.Date("2008-06-30"), 
        ymin=-Inf, ymax=Inf, alpha=.1, fill="blue") + 
      theme(legend.position="bottom") + labs(linetype='') 

然後我想將資產轉換成石油和石油轉爲資產。

我該如何改變?

scale_fill_discrete(labels=c("oil to asset" ,"asset to oil"))

這是行不通的。

請幫幫我。

+1

你想改變'linetype'圖例的標籤嗎?您需要使用'linetype'比例來做到這一點,比如'scale_linetype_manual'或'scale_linetype_discrete',而不是'fill'比例。 – aosmith 2014-10-17 22:16:13

+0

如果連接完全可重複的示例,那將會更容易幫助您。隨機數據或與實際數據的鏈接。 – 2014-10-18 08:23:35

回答

0

這實際上與@aosmith建議的解決方案相同 - 將breaks(而不是labels)加到您的scale_linetype_manual

scale_linetype_manual(values = c("dashed","solid"), breaks=c("oil to asset" ,"asset to oil")) 

我還建議你通過spi$data1 <- factor(spi$data1)讓你spi$data1的一個因素。 ggplot從levels(some_factor_variable中選擇因子排序。您可以通過更改因子水平排序來避免在每個圖表上指定breaksHere是一個示例如何做到這一點。