错误:输入无效:date_trans仅在修改x轴时才使用类Date的对象

时间:2018-02-07 21:06:20

标签: r ggplot2 graphics

我编写了以下代码来生成最后一个图形。问题是我需要修改x轴上显示的日期以使图像更容易理解(理想情况下每两个季度显示一个点)

以下是dataset

以下是代码,在我尝试修改scale_x_date之前一直有效。我试图在几个方面改变日期在情节中引入的方式,但没有成功。我很感激任何帮助。

#rm(list=ls())


library(urca)
library(ggplot2)
library(ggrepel)
library(reshape2)
library(pracma)
library(extrafont)
library(dplyr)
library(lubridate)
library(zoo)

loadfonts(device = "win")

### Data set 

  info <- read.csv("base_completa_frame.csv",header=TRUE,dec=",", sep = ";")
  info <- ts(info,frequency =4, c(1982,1))
  info <- window(info, start=c(2000,4))


### Transf.

data_var <- diff(info,4)/ts(head(info,dim(info)[1]-4), start = c(2001,4), frequency = 4) 
data_var <- ts(data_var,frequency =4, c(2001,4))
data_var <- window(data_var, start = c(2002,4))


data_var[,c(25:27)]         <- window(info[,c(25:27)], start = c(2002,4))
data_var[,c(7,8,13,14)]     <- window(diff(info[,c(7,8,13,14)]), start = c(2002,4))
data_var[,c(25:27,48:50)]   <- window(diff(info[,c(25:27,48:50)],4), start = c(2002,4))

colnames(data_var)          <- colnames(info)

data_var                    <- data_var[,-11:-12]


### Graphs


  # Growth

  time_ref  <- time(data_var)

  time_rec  <- format(date_decimal(as.numeric(time_ref)),"%Y-%m-%d")
  time_rec  <- seq(as.Date(time_rec[1]), length = length(time_rec)[1], by = "quarter")
  time_rec  <- na.omit(time_rec[2*(1:length(time_rec))])

  label_rec <- as.yearqtr(time_rec)

  data_plot <- data.frame(data_var) 
  data_plot[,"time_ref"] <- time_ref

  data_melt <- melt(data_plot, id = "time_ref")


  for (i in nomb_melt){

    ts_ref <- data_melt[which(data_melt$variable == i),]
    ts_ref[,"value"] <- 100*ts_ref[,"value"] 

    sd_ref <- sd(ts_ref[,"value"])

    t_ref  <- qt(0.975,dim(ts_ref)[1]-5)*sd_ref/sqrt(dim(ts_ref)[1]-4)

    test_L <- tail(ts_ref[,"value"],dim(ts_ref)[1]-4) < head(ts_ref[,"value"],dim(ts_ref)[1]-4) - t_ref 
    test_L <- which(test_L == TRUE)

    test_U <- tail(ts_ref[,"value"],dim(ts_ref)[1]-4) > head(ts_ref[,"value"],dim(ts_ref)[1]-4) + t_ref 
    test_U <- which(test_U == TRUE)

    ts_ref <- tail(ts_ref,dim(ts_ref)[1]-4)

    ind_test <- 1:dim(ts_ref)[1]

    ind_test[test_L] <- "Menor"
    ind_test[test_U] <- "Mayor"
    ind_test[-c(test_L,test_U)] <- "Igual"

    ts_ref[,"ind_test"] <- ind_test

    peaks <- findpeaks(ts_ref[,"value"], sortstr=TRUE)[1:4,2]
    mins  <- findpeaks(-ts_ref[,"value"], sortstr=TRUE)[1:4,2]





    p <- ggplot(ts_ref, aes(x = time_ref, y = value, color = variable)) +
         geom_rect(aes(xmin = time_ref,xmax = dplyr::lead(time_ref), 
                       ymin = -Inf, ymax = Inf, fill = factor(ind_test)),
                       alpha = .2, linetype=0) +
         scale_fill_manual(values = alpha(c("yellow","green", "red"), .2)) +
         geom_line() + scale_color_manual(values="black") +
         labs(x =" ", y = "Porcentaje") +
         theme_bw() + 
         theme(plot.title = element_text(hjust = 0.5),
               legend.position="none",
               panel.border = element_blank(),
               axis.line = element_line(colour = "black"), 
               strip.text = element_text(size=14),
               text=element_text(family="Calibri"),
               axis.text.x  = element_text(angle=0)) + 
         geom_label_repel(
            data = ts_ref[peaks,],
            aes(label = format(round(ts_ref[peaks,"value"],2), 2)),
            size = 3,
            nudge_y = 1,
            arrow = arrow(length = unit(0.01, 'npc')),
            point.padding = unit(0.02, 'npc'),
            label.size = NA, fill = "white") +
         geom_label_repel(
            data = ts_ref[mins,],
            aes(label = format(round(ts_ref[mins,"value"],2), 2)),
            size = 3,
            nudge_y = -1,
            arrow = arrow(length = unit(0.01, 'npc')),
            point.padding = unit(0.02, 'npc'),
            label.size = NA, fill = "white") + 
         scale_x_date(breaks = as.Date(time_rec),
                     labels = label_rec)



  print(p)                        

  }

最后,这是一个几乎准备就绪的情节  Graph with no axis modification

1 个答案:

答案 0 :(得分:1)

我也找不到使用scale_x_date解决问题的方法。但是,由于您使用as.yearqtr来创建标签,我尝试了scale_x_yearqtr并且它有效。为简单起见,我将为PIB_Colombia绘图,并且此处仅包含该剧情的代码:

ggplot(ts_ref, aes(x = time_ref, y = value, color = variable)) +
  geom_rect(aes(xmin = time_ref,xmax = dplyr::lead(time_ref), 
                ymin = -Inf, ymax = Inf, fill = factor(ind_test)),
            alpha = .2, linetype=0) +
  scale_fill_manual(values = alpha(c("yellow","green", "red"), .2)) +
  geom_line() + scale_color_manual(values="black") +
  labs(x =" ", y = "Porcentaje") +
  theme_bw() + 
  theme(plot.title = element_text(hjust = 0.5),
        legend.position="none",
        panel.border = element_blank(),
        axis.line = element_line(colour = "black"), 
        strip.text = element_text(size=14),
        #text=element_text(family="Calibri"),
        axis.text.x  = element_text(angle=0)) + 
  geom_label_repel(
    data = ts_ref[peaks,],
    aes(label = format(round(ts_ref[peaks,"value"],2), 2)),
    size = 3,
    nudge_y = 1,
    arrow = arrow(length = unit(0.01, 'npc')),
    point.padding = unit(0.02, 'npc'),
    label.size = NA, fill = "white") +
  geom_label_repel(
    data = ts_ref[mins,],
    aes(label = format(round(ts_ref[mins,"value"],2), 2)),
    size = 3,
    nudge_y = -1,
    arrow = arrow(length = unit(0.01, 'npc')),
    point.padding = unit(0.02, 'npc'),
    label.size = NA, fill = "white") + 
  scale_x_yearqtr(format = "%Y Q%q", n=length(time_rec))

这产生了情节:enter image description here

我使用了您想要包含的中断数量,但您可以通过更改n中的scale_x_yearqtr来控制它。