首页 > 解决方案 > 如何正确使用 scale_x_date

问题描述

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

setwd("C:/Users/USER/Desktop/Jorge")
agua <- read_excel("agua.xlsx")
pbi <- read_excel("PBIagro.xlsx")
str(agua); 
names(agua)[2] <- "Variación";
agua[,1] <- as.Date(agua$Trimestre)

lagpbi <- lag(pbi$PBIAgropecuario, k=1)
pbi[,3]<- lagpbi; pbi <- pbi[-c(1),]; 
names(pbi)[3] <- "PBIlag"

growth <- ((pbi$PBIAgropecuario-pbi$PBIlag)/pbi$PBIlag)*100
Anual_growth <- data.frame(growth); Anual_growth[,2] <- pbi$Año; names(Anual_growth)[2] <- "Año"


# Plot
Agro <- ggplot(Anual_growth, aes(x=Año, y=growth)) +
  geom_line(color="steelblue") + 
  geom_point() +
  geom_text(aes(label = round(Anual_growth$growth, 1)),
            vjust = "inward", hjust = "inward", size=2.5, show.legend = FALSE) +
  xlab("") +
  theme_ipsum() +
  theme(axis.text.x=element_text(angle=60, hjust=1)) +
  ylim(-9.9,13.4) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.line.x = element_blank(), plot.margin = unit(c(1,1,0.5,1),"cm"),
        axis.line.y = element_blank(), axis.text.x=element_text(face = "bold", size=8, 
        angle=1,hjust=0.95,vjust=0.2),
        axis.text.y = element_blank(), axis.title.y=element_blank())+
        scale_x_continuous("Año", labels = as.character(Anual_growth$Año), breaks = Anual_growth$Año)

print(Agro)

在此处输入图像描述

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

标签: rggplot2

解决方案


您可以 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() 

在此处输入图像描述

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

在此处输入图像描述

3.

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

在此处输入图像描述


推荐阅读