簡體   English   中英

使用ggplot2繪制xts對象

[英]Plotting an xts object using ggplot2

我想用ggplot2繪制一個xts對象,但是收到錯誤。 這是我正在做的事情:

dates <- c("2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01")
value <- as.numeric(c(3, 4, 5, 6, 5))
new_df <- data_frame(dates, value)
new_df$dates <- as.Date(dates)
new_df <- as.xts(new_df[,-1], order.by = new_df$dates)

現在我嘗試使用ggplot2繪制它:

ggplot(new_df, aes(x = index, y = value)) + geom_point()

我收到以下錯誤:

錯誤(函數(...,row.names = NULL,check.rows = FALSE,check.names = TRUE,:參數意味着不同的行數:0,5

我不太確定我做錯了什么。

將小寫'指數'改為大寫'指數'

ggplot(new_df, aes(x = Index, y = value)) + geom_point()

動物園中的autoplot.zoo方法(動物園由xts自動拉入)也將使用ggplot2為xts對象創建繪圖。 它支持ggplot2的+ ...如果你需要額外的geoms。 ?autoplot.zoo

library(xts)
library(ggplot2)
x_xts <- xts(1:4, as.Date("2000-01-01") + 1:4) # test data

autoplot(x_xts, geom = "point")

zoo還有fortify.zoo ,它將動物園或xts對象轉換為data.frame:

fortify(x_xts)

贈送:

       Index x_xts
1 2000-01-02     1
2 2000-01-03     2
3 2000-01-04     3
4 2000-01-05     4

fortify泛型在ggplot2中,所以如果你沒有加載ggplot2,那么直接使用fortify.zoo(x_xts)

有關更多信息,請參閱?fortify.zoo

你需要使用xts對象嗎?

您可以在不使用xts情況下繪制日期/時間。 以下是使用您在上面提供的內容的示例。 除此之外,您可以將其格式化。

dates <- c("2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01")
value <- as.numeric(c(3, 4, 5, 6, 5))
new_df <- data.frame(dates, value)
new_df$dates <- as.Date(dates)

require(scales)
ggplot(new_df, aes(x = dates, y = value)) + geom_point() + 
scale_x_date(labels = date_format("%Y-%m-%d"), breaks = date_breaks("1 month")) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggsave("time_plot.png", height = 4, width = 4)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM