简体   繁体   中英

Changing x axis label in GGPlot2

I have an r data set which has money spendings spread across months, and also grouped by years.

Year|Mth_Year|Mth_Spend
2004|01-2004|42507163
2004|02-2004|3377592
2006|10-2006|3507636
2006|11-2006|4479139
2006|12-2006|2439603

I need to display the monthly information (grouped year wise), so that some quick comparisons can be done.

I am using the ggplot, geom_bar options to display the monthly spends. Below is the code, I use.

ggplot(data=yearly_spending,aes(x=Year,y=Mth_Spend,fill=Mth_Year))+
  geom_bar(stat="identity",color="black",position=position_dodge())+
  theme(axis.text.x=element_text(angle=90,hjust=1))

When I use this code, the bar chart is getting displayed. But in X Axis, only the years (2004, 2005 & 2006) are displayed. Can I get the months also displayed above the years. The years can appear horizontally, and while months can be placed vertically.

Thank you for all the suggestions. Using the scales package and lubridate to convert strings into date, I could solve the issue.

ggplot(data=monthly_spend_catwise,aes(x=Mth_Year,y=TotSpending,fill=Type))+
scale_x_date(labels=date_format("%m-%Y"),date_breaks = "1 month")+
theme(axis.text.x=element_text(angle=45,hjust=1,vjust=0.5))+
geom_bar(stat="identity",color="black",position=position_dodge())

I had formatted the dates in Mth_Year (instead of 01-2004, made it into 01-01-2004), using the below code.

spending$Mth_Year <- as.Date(paste("01",spending$Mth_Year,sep="-"),"%d-%m-%y")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM