如何正确使用scale_x_date

0 r ggplot2

我是 R 的新用户,希望你能帮助我。

\n\n
setwd("C:/Users/USER/Desktop/Jorge")\nagua <- read_excel("agua.xlsx")\npbi <- read_excel("PBIagro.xlsx")\nstr(agua); \nnames(agua)[2] <- "Variaci\xc3\xb3n";\nagua[,1] <- as.Date(agua$Trimestre)\n\nlagpbi <- lag(pbi$PBIAgropecuario, k=1)\npbi[,3]<- lagpbi; pbi <- pbi[-c(1),]; \nnames(pbi)[3] <- "PBIlag"\n\ngrowth <- ((pbi$PBIAgropecuario-pbi$PBIlag)/pbi$PBIlag)*100\nAnual_growth <- data.frame(growth); Anual_growth[,2] <- pbi$A\xc3\xb1o; names(Anual_growth)[2] <- "A\xc3\xb1o"\n\n\n# Plot\nAgro <- ggplot(Anual_growth, aes(x=A\xc3\xb1o, y=growth)) +\n  geom_line(color="steelblue") + \n  geom_point() +\n  geom_text(aes(label = round(Anual_growth$growth, 1)),\n            vjust = "inward", hjust = "inward", size=2.5, show.legend = FALSE) +\n  xlab("") +\n  theme_ipsum() +\n  theme(axis.text.x=element_text(angle=60, hjust=1)) +\n  ylim(-9.9,13.4) + \n  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),\n        axis.line.x = element_blank(), plot.margin = unit(c(1,1,0.5,1),"cm"),\n        axis.line.y = element_blank(), axis.text.x=element_text(face = "bold", size=8, \n        angle=1,hjust=0.95,vjust=0.2),\n        axis.text.y = element_blank(), axis.title.y=element_blank())+\n        scale_x_continuous("A\xc3\xb1o", labels = as.character(Anual_growth$A\xc3\xb1o), breaks = Anual_growth$A\xc3\xb1o)\n\nprint(Agro)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此输入图像描述

\n\n

问题是它显示了所有年份,但我只想要成对年份(在 X 轴)或步长等于 2 的年份。\n我希望你能真正帮助我。\n谢谢。\n请注意,X 轴变量是一个数字字符串。

\n

小智 6

您可以将类似的内容添加 scale_x_date(date_breaks = "2 years", date_labels = "%Y")到您的 ggplot.

这就是我的数据的样子,因为你还没有发布你的数据。date我正在x 轴上绘制一个类型。

1.

ggplot(mydata) +
 aes(x = date, y = number, color = somevar) +
 geom_line() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  1. ggplot(mydata) +
      aes(x = date, y = number, color = somevar) +
      geom_line() +
    scale_x_date(date_breaks = "1 year", date_labels = "%Y")
    
    Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

3.

ggplot(mydata) +
  aes(x = date, y = number, color = somevar) +
  geom_line() +
scale_x_date(date_breaks = "2 years", date_labels = "%Y")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述