r - 使用scale_x_date更改轴格式时出错

标签 r graph ggplot2

亲爱的智人同胞们,

我创建了this使用下面的代码绘制图表(除非没有 +scale_x_date)。

我用来执行此操作的数据集被发现 HERE 。它看起来像这样:

GFC1CARi<-read.csv("demo.csv")
head(GFC1CARi)
  X         XX   variable       value    Var
1 1 2008-07-17 Financials 0.001772705 Financ
2 2 2008-07-18 Financials 0.017306086 Financ
3 3 2008-07-21 Financials 0.010745136 Financ
4 4 2008-07-22 Financials 0.021152194 Financ
5 5 2008-07-23 Financials 0.031195805 Financ
6 6 2008-07-24 Financials 0.026534444 Financ

正如您将在图片中看到的那样,x 轴显示日期,例如“八月”、“九月”......。但是,我希望它类似于“08/2007”、“09/2007”......。因此,我的尝试如下所示,但它不起作用。

p <- ggplot(data=GFC1CARi,aes(x=XX, y=value, colour=Var)) +
        geom_line() + 
        opts(legend.position = "none") + 
        xlab(" ") + 
        ylab("Cumulative abnormal return") + 
        scale_x_date(labels = date_format("%m/%Y"),breaks = "1 month")

p <- direct.label(p+xlim(min(GFC1CARi$XX), max(GFC1CARi$XX)+20))

我已经尝试了 breaks = ??date_format 的许多其他变体,但我无法显示 %m/%Y,它总是会显示是“八月”..“九月”..“十月”。根据乔兰的要求:

> str(GFC1CARi)
'data.frame':   1730 obs. of  5 variables:
 $ X       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ XX      : POSIXct, format: "2008-07-17" "2008-07-18" "2008-07-21" "2008-07-22" ...
 $ variable: Factor w/ 10 levels "Financials","Industrials",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.00177 0.01731 0.01075 0.02115 0.0312 ...
 $ Var     : chr  "Financ" "Financ" "Financ" "Financ" ...

我什至尝试将日期格式从 POSIXct 更改为 as.Date,如下所示:

GFC1CARi[,2]<-as.Date(GFC1CARi[,2])
str(GFC1CARi)
'data.frame':   1730 obs. of  5 variables:
 $ X       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ XX      : Date, format: "2008-07-16" "2008-07-17" ...
 $ variable: Factor w/ 10 levels "Financials","Industrials",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.000983 0.015822 0.008339 0.017987 0.027186 ...
 $ Var     : chr  "Financ" "Financ" "Financ" "Financ" ...

这并不能解决问题。相反,X 轴现在是 { "Oct", "Jan", "Apr"},就是这样。

谢谢大家。

最佳答案

抱歉,我太笨了。我认为您遇到的错误是在尝试使用directlabels之前发生的,而不是之后发生的。

xlim 的调用只是简单地破坏 x 轴格式。只需将 scale_x_date 调用放入 direct.labels 命令中即可对我起作用:

p <- direct.label(p + 
                  xlim(min(dat$XX), max(dat$XX)+20) + 
                  scale_x_date(labels = date_format("%m/%Y"),breaks = "1 month"))

enter image description here

关于r - 使用scale_x_date更改轴格式时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375276/

相关文章:

r - ggplot2时间序列的阴影包络

r - ggplot2 中的多层

algorithm - 找到 k 个矩形,使它们覆盖最大数量的点

python - 使用 DataFrame 绘制双轴图

r - 每个条形带有颜色渐变的堆叠条形图

r - ggplot : bizarre issue adding labels in time-series data

R折叠并自动填充行中的空白

r - 在R中,处理错误:ggplot2不知道如何处理数值类的数据

r - knitr 用中文编译文档

algorithm - 计算距 m 个给定节点的距离小于 k 的所有节点的最佳方法