R 如何正确使用scale_x_date

R 如何正确使用scale_x_date,r,ggplot2,R,Ggplot2,我是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

我是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)
setwd(“C:/Users/USER/Desktop/Jorge”)

agua如果您想要成对年份,并且由于x轴变量是数字,您可以在
scale\u x\u continuous
中指定
breaks
参数只应取
偶数

下面是如何使用以下小示例进行此操作:

year=1998:2020
值=rnorm(23,平均值=3)
df=数据帧(年,值)
图书馆(GG2)
ggplot(df,aes(x=年份,y=数值))+
几何点()+
geom_线()+
连续缩放(间隔=年[年%%2==0])

反过来,如果您想要奇数年,只需指定
scale\u x\u continuous(breaks=year[year%%2!=0])

因此,在代码中,您应该编写:

scale_x_continuous(中断=年度增长$Año[年度增长$Año%%2==0])

它回答了您的问题吗?

您可以添加以下内容
scale\u x\u date(date\u breaks=“2年”,date\u labels=“%Y”)
到ggplot

这就是我的数据的外观,因为你还没有发布你的数据。我正在x轴上绘制类型
日期

一,

  • 三,

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