以日期格式旋转轴标签 [英] rotating axis labels in date format

查看:130
本文介绍了以日期格式旋转轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有人知道如何使用ggplot2在日期格式中旋转轴刻度?
我想用x轴上45°角的Date-Month(例如1985-5)标签。

数据样本:

 站点日期Ptot 
A 1980-02 16
A 1980-03 19
A 1980-04 40
A 1980-05 48
A 1980-06 NA
A 1980-07 18.5
A 1980-08 24.6
B 1980-07 50.8
B 1980-08 28.9
B 1980-09 32.9
B 1980-10 47.9
B 1980-11 16.3

我试过了:

  library(ggplot2)
图书馆(比例)

plot < - ggplot(data = na.omit(data),aes(x = Date,y = Ptot,group = Station))+
geom_line ()+
facet_grid(Station〜。)+
scale_x_date(breaks =year,labels = date_format(%Y-%m))+
xlab(Year) +
ylab(Prec(mm))+
labs(color =Station)+
theme(axis.text.x = element_text(angle = 45,hjust = 1) )+
theme_bw()

plot

但它没有't work。



谢谢!

Date 作为日期。由于它没有提供日期,所以您应该为每个日期添加例如01并将其转换。

  data $ Date< -as.Date(paste(data $ Date, -  01,sep =),format =%Y-%m-%d)

要在x轴下正确放置标签,您不仅应该设置 angle = ,还应该设置 hjust = 1 ,以确保标签的末尾位于刻度标记下方。 theme_bw()应放置在轴文本的主题说明之前。

  ggplot(data = na.omit(data),aes(x = Date,y = Ptot,group = Station))+ 
geom_line()+
facet_grid(Station〜。)+ $ b $ (scale =month,labels = date_format(%Y-%m))+
xlab(Year)+
ylab(Prec(mm))+ theme_bw )+
主题(axis.text.x = element_text(angle = 45,hjust = 1))


does anyone know how to rotate axis ticks in the date format with ggplot2? I want to get labels with "Date-Month" (ex. "1985-5") with a 45° angle on the x axis.

data sample:

Station Date Ptot
A 1980-02 16
A 1980-03 19
A 1980-04 40
A 1980-05 48
A 1980-06 NA
A 1980-07 18.5
A 1980-08 24.6
B 1980-07 50.8
B 1980-08 28.9
B 1980-09 32.9
B 1980-10 47.9
B 1980-11 16.3

I tried this:

library(ggplot2)
library(scales)

plot <- ggplot(data=na.omit(data), aes(x=Date, y=Ptot, group=Station))+
   geom_line()+
   facet_grid(Station~.)+
   scale_x_date(breaks = "year", labels=date_format("%Y-%m"))+
   xlab("Year")+
   ylab("Prec (mm)")+
   labs(colour = "Station")+
   theme(axis.text.x = element_text(angle = 45, hjust = 1))+
   theme_bw()

plot

but it doesn't work.

Thanks!

解决方案

First, you should make column Date as date. As it do not have the day provided, you should add for example 01 to each date and convert them.

data$Date<-as.Date(paste(data$Date,"-01",sep=""),format="%Y-%m-%d")

To get correct placement of labels under x axis you should set not just angle= but also hjust=1 to ensure that end of the label is placed under the tick mark. Also theme_bw() should be placed before theme specification of axis texts.

ggplot(data=na.omit(data), aes(x=Date, y=Ptot, group=Station))+
  geom_line()+
  facet_grid(Station~.)+
  scale_x_date(breaks = "month", labels=date_format("%Y-%m"))+
  xlab("Year")+
  ylab("Prec (mm)")+theme_bw()+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

这篇关于以日期格式旋转轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆