R项目:绘制数据框架

时间:2011-04-03 04:57:05

标签: r plot dataframe

9059 2011-02-18                 2.81
9060 2011-02-21                 <NA>
9061 2011-02-22                 2.72
9062 2011-02-23                 2.75
9063 2011-02-24                 2.73
9064 2011-02-25                  2.7
9065 2011-02-28                 2.73
9066 2011-03-01                 2.75
9067 2011-03-02                 2.77
9068 2011-03-03                 2.79
9069 2011-03-04                 2.81
9070 2011-03-07                 2.81
9071 2011-03-08                 2.83
9072 2011-03-09                 2.78
9073 2011-03-10                 2.72
9074 2011-03-11                 2.76
9075 2011-03-14                 2.75
9076 2011-03-15                  2.7

以上是名为'mydata'的数据框的片段。第一列的名称是V1,第二列的名称是V2。第一列包含使用as.Date()函数转换的日期。

我想在x-y网格上绘制它,x轴上的列为-1,y轴上的列为2。我已经尝试了几个小时没有成功的各种组合。

我试过

> plot(mydata[,1], mydata[,2])

这会导致R控制台挂起,因为它似乎呈现出无意义的东西。

2 个答案:

答案 0 :(得分:1)

这对我有用(虽然我不知道它是否产生了所需的输出?

usr <- textConnection("9059 2011-02-18                 2.81
9060 2011-02-21                 <NA>
9061 2011-02-22                 2.72
9062 2011-02-23                 2.75
9063 2011-02-24                 2.73
9064 2011-02-25                  2.7
9065 2011-02-28                 2.73
9066 2011-03-01                 2.75
9067 2011-03-02                 2.77
9068 2011-03-03                 2.79
9069 2011-03-04                 2.81
9070 2011-03-07                 2.81
9071 2011-03-08                 2.83
9072 2011-03-09                 2.78
9073 2011-03-10                 2.72
9074 2011-03-11                 2.76
9075 2011-03-14                 2.75
9076 2011-03-15                  2.7")

usr <- read.table(usr, header = FALSE)[-1] #remove the first column

with(usr, plot(V3 ~ V2))

答案 1 :(得分:1)

我做了以下工作:

> x2 <- read.zoo("2_yr_tsy_rate.txt", format="%m/%d/%Y", sep=",", na.strings="ND")
>
> x10 <- read.zoo("10_yr_tsy_rate.txt", format="%m/%d/%Y", sep=",", na.strings="ND")
>
> sprd <- x10 - x2
>
> plot(sprd)

这有效...但是如果我使用read.csv加载数据并尝试更改数据对象则是一场噩梦。

现在我有另一个问题。情节有效,但x轴标签每10年报告一次。我的数据是利率差可以追溯到1976年。我希望x轴标签是季度的。我尝试了各种各样的事情,包括以下但是有错误。

> plot(as.yearqtr(sprd), sprd, type='l')
Error in if (del == 0 && to == 0) return(to) : 
  missing value where TRUE/FALSE needed

这是str(我的对象)

的输出
> str(sprd)
‘zoo’ series from 1976-06-01 to 2011-03-31
  Data: num [1:9088] 0.68 0.71 0.7 0.77 0.79 0.79 0.82 0.86 0.83 0.83 ...
  Index: Class 'Date'  num [1:9088] 2343 2344 2345 2346 2349 ...
>