R闪亮日期仅以5年间隔显示

时间:2017-05-30 15:56:55

标签: r plot shiny

以下是我在R情节中使用的日期

dates <- c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", 
           "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017")

当我绘制图表时,这里是代码,日期仅以每年5个间隔显示,而不是每年显示。

  plot(x = dates, y=Comp_selected_DF[idx_country, 2:18], type = "l"
         , xlab = "", ylab = "", col="grey20", ylim = c(-2, overall_max_z), lwd=3)
    mtext("Financial Vulnerability Indicator", side=3, adj=0, line=1.2, cex=2, font=2)
    mtext("Z-Score", side=3, adj=0, line=0.1, cex=1, font=0.5)
    lines(dates, Bank_selected_DF[idx_country, 2:18], col="green2", lwd=3)
    lines(dates, Curr_selected_DF[idx_country, 2:18], col="purple", lwd=3)
    lines(dates, Sover_selected_DF[idx_country, 2:18], col="red", lwd=3)
    lines(dates, Sudden_selected_DF[idx_country, 2:18], col="orange", lwd=3)
    legend(
      "bottom", 
      lty=c(1,1,1,1), 
      col=c("grey20", "green2", "purple", "red", "orange"), 
      legend = c("Composite", "Banking", "Currency", "Sovereign", "Sudden Stop")
      ,ncol=5
    )

编辑:这是我运行代码时得到的结果。似乎传说现在已经散布开来。 enter image description here

1 个答案:

答案 0 :(得分:1)

在基本图形中,如果要对轴进行精细控制,可以使用整数绘制数据并明确设置标签。

进行了以下更改:

  • 伪造了一些数据进行实验
  • 创建了一个新的整数值x轴范围(1:17)
  • 使用axis调用将dates映射到这些值
  • 正如Ryan Morton建议的那样,使用las=2将x轴标签旋转90度。
  • 使用lines参数将图例中的线条类型设置为3(如lwd)。

所以这就是代码:

dates <- c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", 
           "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017")

# fake up some data
set.seed(123)
gendf <- function(){
  cname <- c("USA","Mexico","Canada")
  df <- data.frame(dum=1:18)
  for (i in 1:3){
    df[[cname[i]]] <- cumsum(rnorm(18,1,1))
  }
  df$dum <- NULL
  rownames(df) <- c("country",dates)
  ndf <- as.data.frame(t(df))
  ndf$country <- cname
  ndf
}
Comp_selected_DF <- gendf()
Bank_selected_DF <- gendf()
Curr_selected_DF <- gendf()
Sover_selected_DF <- gendf()
Sudden_selected_DF <- gendf()

overall_max_z <- max(Comp_selected_DF[,2:18])
idx_country <- 1


# Now plot it out
xvals <- 1:17   # our new xvalues (instead of dates)

plot(x = xvals, y=Comp_selected_DF[idx_country, 2:18], type = "l"
     , xlab = "", ylab = "", col="grey20", ylim = c(-2, overall_max_z), lwd=3,las=2)
mtext("Z-Score", side=3, adj=0, line=0.1, cex=1, font=0.5)
axis(1,at=xvals,label=dates, cex.axis=1, las=2)
mtext("Financial Vulnerability Indicator", side=3, adj=0, line=1.2, cex=2, font=2)
 lines(xvals, Bank_selected_DF[idx_country, 2:18], col="green2", lwd=3)
 lines(xvals, Curr_selected_DF[idx_country, 2:18], col="purple", lwd=3)
 lines(xvals, Sover_selected_DF[idx_country, 2:18], col="red", lwd=3)
 lines(xvals, Sudden_selected_DF[idx_country, 2:18], col="orange", lwd=3)
 legend(
   "bottom", 
   lty=c(1,1,1,1), 
   lwd=c(3,3,3,3), 
   col=c("grey20", "green2", "purple", "red", "orange"), 
   legend = c("Composite", "Banking", "Currency", "Sovereign", "Sudden Stop")
   ,ncol=5
 )

这就是它的样子:

enter image description here