使用scale_x_date指定ggplot2的第一个和最后一个刻度线 [英] Specification of first and last tick marks with ggplot2 with scale_x_date
问题描述
我希望能够指定出现在由ggplot2生成的图中的第一个和最后一个刻度线,但是会遇到一些问题。这是一些代码。
#生成向量天数
dateVec< -seq(from = as.Date(2011-11- )= to as.Date(2012-11-23),by =days)
#某些随机数据
myData< -rnorm(length(dateVec))
#绘制
qplot(dateVec,myData)+
scale_x_date(breaks =4 weeks,limits = c(min(dateVec),max = max(dateVec)))+
主题(axis.text.x = element_text(size = 10,angle = 45,color =black,vjust = 1,hjust = 1))
请注意,日期向量中的最小日期为2011-11-21,最大日期为2012-11-23,并且我已指定了图的限制。然而,情节似乎有所延长。
有没有办法强制第一个和最后一个刻度符合scale_x_date中指定的实际限制?
<为了确保axis不被扩展,你可以添加参数
expand = c( 0,0)
至 scale_x_date()
。qplot(dateVec,myData)+
pre>
scale_x_date(breaks =4 weeks,limits = c(min(dateVec),max = max(dateVec)),expand = c(0,0))+
主题(axis.text.x = element_text(size = 10,angle = 45,color =black,vjust = 1,hjust = 1))
UPDATE
如果您需要以最小和最大日期开始的刻度,那么您可以定义自己的中断。为此,我制作了包含最小和最大日期的矢量
break.vec
以及它们之间的月份日期。然后使用此向量在scale_x_date()
中设置中断。
break .vec< -c(as.Date(2011-11-21),
seq(from = as.Date(2011-12-01),to = as.Date(2012-11 (=month),
as.Date(2012-11-23))
qplot(dateVec,myData)+
scale_x_date break = break.vec)+
theme(axis.text.x = element_text(size = 10,angle = 45,color =black,vjust = 1,hjust = 1))
I would like to be able to specify the first and last tick marks which appear in a plot produced by ggplot2, but an running into some problems. Here is some code.
#Produce a vector of days dateVec<-seq(from=as.Date("2011-11-21"), to=as.Date("2012-11-23"), by="days") #Some randome data myData<-rnorm(length(dateVec)) #Plot it qplot(dateVec, myData) + scale_x_date(breaks="4 weeks", limits=c(min(dateVec), max=max(dateVec)))+ theme(axis.text.x=element_text(size=10, angle=45, colour="black", vjust=1, hjust=1))
Notice that the minimum date in the date vector is 2011-11-21 and the maximum date is 2012-11-23 and that I have specified the limits of the plot. However, the plot seems extended by some amount.
Is there a way to force the first and last tick marks to correspond to the actual limits specified in scale_x_date?
Thanks!
解决方案To ensure that axis is not expanded you can add argument
expand=c(0,0)
toscale_x_date()
.qplot(dateVec,myData) + scale_x_date(breaks="4 weeks",limits=c(min(dateVec),max=max(dateVec)),expand=c(0,0)) + theme(axis.text.x = element_text(size=10,angle=45,colour="black",vjust=1,hjust=1))
UPDATE
If you need ticks that start with minimal and maximal dates then you can define your own breaks. For this I made vector
break.vec
containing minimal and maximal date as well as dates by month between them. Then used this vector to set breaks inscale_x_date()
.break.vec<-c(as.Date("2011-11-21"), seq(from=as.Date("2011-12-01"), to=as.Date("2012-11-01"), by="month"), as.Date("2012-11-23")) qplot(dateVec,myData) + scale_x_date(breaks=break.vec) + theme(axis.text.x = element_text(size=10,angle=45,colour="black",vjust=1,hjust=1))
这篇关于使用scale_x_date指定ggplot2的第一个和最后一个刻度线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!