如何在R中更改為xts物件建立的繪圖線條顏色?


要更改在R中為xts物件建立的繪圖的線條顏色,我們可以按照以下步驟操作:

  • 首先,建立一個數據框。

  • 然後,將此資料框轉換為xts物件。

  • 使用預設顏色建立xts物件資料的繪圖。

  • 然後,使用不同的顏色建立xts物件資料的繪圖。

建立資料框

讓我們建立一個如下所示的資料框:

Dates<-seq.POSIXt(from=as.POSIXct("2021-01-01"),to=as.POSIXct("2021-01-
25"),length.out=25)
Score<-sample(1:100,25)
df<-data.frame(Dates,Score)
df

執行上述指令碼後,將生成以下輸出(此輸出由於隨機化而會因您的系統而異):

      Dates   Score
1  2021-01-01  85
2  2021-01-02  60
3  2021-01-03  80
4  2021-01-04  95
5  2021-01-05  93
6  2021-01-06  43
7  2021-01-07  57
8  2021-01-08  27
9  2021-01-09  74
10 2021-01-10  84
11 2021-01-11  18
12 2021-01-12  16
13 2021-01-13  72
14 2021-01-14  100
15 2021-01-15  23
16 2021-01-16  50
17 2021-01-17  2
18 2021-01-18  31
19 2021-01-19  54
20 2021-01-20 73
21 2021-01-21 33
22 2021-01-22 17
23 2021-01-23 6
24 2021-01-24 12
25 2021-01-25 98

將資料框轉換為xts物件

載入xts包並將df轉換為xts物件:

Dates<-seq.POSIXt(from=as.POSIXct("2021-01-01"),to=as.POSIXct("2021-01-
25"),length.out=25)
Score<-sample(1:100,25)
df<-data.frame(Dates,Score)
library(xts)
df_ts<-xts(df$Score,df$Dates)
df_ts

輸出

   [,1]
2021-01-01 85
2021-01-02 60
2021-01-03 80
2021-01-04 95
2021-01-05 93
2021-01-06 43
2021-01-07 57
2021-01-08 27
2021-01-09 74
2021-01-10 84
2021-01-11 18
2021-01-12 16
2021-01-13 72
2021-01-14 100
2021-01-15 23
2021-01-16 50
2021-01-17 2
2021-01-18 31
2021-01-19 54
2021-01-20 73
2021-01-21 33
2021-01-22 17
2021-01-23 6
2021-01-24 12
2021-01-25 98

建立xts物件的繪圖

使用plot函式建立xts物件的繪圖:

Dates<-seq.POSIXt(from=as.POSIXct("2021-01-01"),to=as.POSIXct("2021-01-
25"),length.out=25)
Score<-sample(1:100,25)
df<-data.frame(Dates,Score)
library(xts)
df_ts<-xts(df$Score,df$Dates)
plot(df_ts)

輸出

建立具有不同顏色線條的相同繪圖

使用lines函式建立具有不同線條顏色的xts物件的繪圖,如下所示:

Dates<-seq.POSIXt(from=as.POSIXct("2021-01-01"),to=as.POSIXct("2021-01-
25"),length.out=25)
Score<-sample(1:100,25)
df<-data.frame(Dates,Score)
library(xts)
df_ts<-xts(df$Score,df$Dates)
plot(df_ts)
lines(df_ts,col="red")

輸出

更新於:2021年8月14日

202 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告