2017-04-11 128 views
1

我想繪製一個使用ggplot2的xts對象,但得到一個錯誤。下面是我在做什麼:使用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() 

我得到以下錯誤:

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 5

我不太清楚我做錯了什麼。

回答

4

變小寫的「指數」爲大寫「索引」

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

你需要使用一個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) 

enter image description here

2

在動物園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") 

動物園也有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瞭解更多信息。