Dropping some x-axis values in ggplot

2019-08-06 15:46发布

问题:

My dataframe called Finalcombined looks like this: I have the following graph:

And the following code:

Labourproductivity<- ggplot(Finalcombined, aes(x = quarter, y = LabourProductivity, group=1))+geom_line(colour="black", size=0.5) +
  labs(x="Time", y=("Labour Productivity"))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1, ))+
  geom_point(colour="black", size=2, shape=16)+
  geom_smooth(aes(group=1))+
  theme(axis.text=element_text(size=13),axis.title=element_text(size=16,face="bold"))+
  theme(panel.grid.major = element_line(colour = "white", size=0.50),panel.grid.minor = element_line(colour = "white", size=0.16))
Labourproductivity

My question is how can get rid of some of the values indicated on the x-axis but still have the same graph. I would only like to include (2004 Q1, 2005 Q1, 2006 Q1) and so on. How would I go about this? Thank you for your help!

回答1:

Add below to your ggplot

scale_x_discrete(breaks=Finalcombined$quarter[grepl("Q1",Finalcombined$quarter)])

Example:

require("ggplot2")

#dummy data
Q <- paste(sort(rep(2004:2013,4)),paste0("Q",1:4))
Finalcombined <-
  data.frame(quarter= Q,
             LabourProductivity=runif(length(Q)))

#plot
ggplot(Finalcombined,
       aes(x = quarter,
           y = LabourProductivity,
           group=1)) + 
  geom_line(colour="black", size=0.5) +
  labs(x="Time", y=("Labour Productivity")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, )) +
  geom_point(colour="black", size=2, shape=16) +
  geom_smooth(aes(group=1)) +
  theme(axis.text=element_text(size=13),axis.title=element_text(size=16,face="bold")) +
  theme(panel.grid.major = element_line(colour = "white", size=0.50),panel.grid.minor = element_line(colour = "white", size=0.16)) +
  #change X axis labels
  scale_x_discrete(breaks=Finalcombined$quarter[grepl("Q1",Finalcombined$quarter)])



标签: r ggplot2