開始使用免費開始

更進階的股價走勢圖(2)

在這個練習中,你會為剛才建立的圖表加入圖例,內容包含公司名稱,以及最新股利的日期與金額。

請將預先寫好的程式碼補上以下變數(兩家公司各自的股利金額與日期):

  • citi_div_value
  • citi_div_date
  • micro_div_value
  • micro_div_date

請記得,繪製線條的預設顏色是黑色;而在 legend() 中的 legendcollty 參數,其向量長度都應與你圖上所繪的時間序列數量相同。

如果看不到完整的圖例,繪圖後試著把圖表切換為全螢幕。讓我們把圖表做得更精緻一些吧!

本練習屬於課程

在 R 視覺化時間序列資料

檢視課程

練習說明

  • 建立與前一個練習相同的圖(此步驟已替你完成)
  • 使用上面已載入的變數建立將用於圖例的字串 microciti
  • "Microsoft div of $0.39 on 15 Nov. 2016"
  • "Citigroup div of $0.16 on 13 Nov. 2016"
  • 在圖表的右下角建立圖例,使用你剛建立的 microciti 字串作為文字,為標籤設定合適的顏色,並使用一般實線

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Same plot as the previous exercise
plot(data$microsoft, main = "Dividend date and amount")
lines(data$citigroup, col = "orange", lwd = 2)
axis(side = 4, at = pretty(data$citigroup), col = "orange")

# Create the two legend strings
micro <- paste0("Microsoft div. of ", ___," on ", ___)
citi <- paste0("Citigroup div. of ", ___," on ", ___)

# Create the legend in the bottom right corner
legend(x = ___, legend = c(___, ___), col = c(___, ___), lty = c(___, ___))
編輯並執行程式碼