首页 文章

在GGPlot2中更改x轴标签

提问于
浏览
0

我有一个r数据集,它有几个月的资金支出,也按年分组 .

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

我需要显示月度信息(按年分组),以便进行一些快速比较 .

我使用ggplot,geom_bar选项显示每月花费 . 以下是我使用的代码 .

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))

当我使用此代码时,条形图将显示 . 但在X轴中,仅显示年份(2004年,2005年和2006年) . 我可以在这些年份之上显示月份 . 这些年份可以水平出现,而月份则可以垂直放置 .

1 回答

  • 0

    谢谢你提出的所有建议 . 使用scale包和lubridate将字符串转换为日期,我可以解决这个问题 .

    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())
    

    我使用下面的代码将日期格式化为Mth_Year(而不是01-2004,使其成为01-01-2004) .

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

相关问题