简体   繁体   English

R:如何将年-年放在图的X轴上。

[英]R: How do you put the month - year on the X axis of a plot.zoo multiple plot?

In a shiny app I would like to put the month - year (ie "Jan- 13", "Feb- 13") of a plot.zoo multiple line plot. 在一个闪亮的应用程序中,我想输入plot.zoo多线图的月份-年(即“ Jan-13”,“ Feb-13”)。 I have googled and it looks like you have to use a panel and if statement to find the last plot but I still cannot get the month - year to show up on the x axis. 我已经用谷歌搜索,看起来您必须使用面板和if语句来找到最后一个图,但是我仍然无法获得月份-年在x轴上显示。

Here is code you can run: 这是您可以运行的代码:

library("zoo")

Factors <- matrix(seq(from=1, to=9, by=1), nrow=3,ncol=3)
Factors
datesNumeric <- cbind(20130101, 20130220,20130801)
dates <- as.Date(as.character(datesNumeric), format="%Y%m%d")
ticks <- seq(dates[1], dates[length(dates)], by = "1 month") #I make some ticks
ticks

my.panel <- function(x, y, ..., pf = parent.frame()) {
  grid(NA,NULL)
  #abline(v=seq(1,168,24),col = "lightgray", lty = "dotted", lwd = par("lwd"))
  lines(x, y, ...)

  #if bottom panel
  if (with(pf, length(panel.number) == 0 ||panel.number %% nr == 0 || panel.number == nser)) {
    #axis(1, at = ticks, labels = ticks)
    axis.Date(1, at = ticks, format= "%m-%y", las = 1)
  }
 }

plot(as.zoo(Factors), main="Factors 1,2, & 3", ylab=c("Factor 1","Factor 2","Factor 3") ,      xlab= "Date", panel = my.panel,yax.flip=FALSE,col=1:3,xaxt="n")

Any idea how to get dates (ie "Jan- 13", "Feb- 13", etc...) to show up on the x axis? 是否知道如何获取日期(即“ Jan-13”,“ Feb-13”等)以显示在x轴上? thank you. 谢谢。

You should create a reproducible example. 您应该创建一个可复制的示例。 plot.zoo is just a base plot. plot.zoo只是一个基本情节。 So to format axis with dates you should use axis.Date . 因此,要使用日期格式化轴,应使用axis.Date

x.Date <- as.Date(paste(2003,  c(1, 3, 7, 9, 14), 02,sep = "-"))
x <- zoo(rnorm(5), x.Date)
plot(x,xaxt="n")
axis.Date(1, at = x.Date, format= "%m-%y", las = 1)

在此处输入图片说明

EDIT after op update: 操作更新后进行编辑

You should create a valid zoo object. 您应该创建一个有效的Zoo对象。

 plot(zoo(x=Factors,order.by=ticks),  ## here your error
     main="Factors 1,2, & 3", ylab=c("Factor 1","Factor 2","Factor 3") ,    
 xlab= "Date", panel = my.panel,yax.flip=FALSE,col=1:3,
     format='%b-%y') ## format labels 

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM