[英]Midpoint for Date axis in ggplot
I want to add some labels to a plot on which the x-axis is a Date. 我想在x轴是日期的绘图上添加一些标签。 I want the label to be centered around the middle. 我希望标签在中间居中。 How do I find the midpoint on the x-axis? 如何在x轴上找到中点?
Example: 例:
example <- data.frame(time = c("02/26/11", "05/26/10", "05/27/10", "05/28/10",
"05/29/10", "06/27/10", "06/30/10", "10/27/10",
"10/27/10", "12/26/12"),
value = c(5, 1, 7, 8, 11, 20, 14, 1, 20, 12))
example$time <- as.Date(example$time, format = "%m/%d/%Y")
ggplot(example, aes(x = time, y = value)) + geom_point() +
scale_x_date(labels = date_format("%b%Y"),
breaks = "3 month",
minor_breaks = "1 month")
Now, I want to use geom_text to add a text lable that has x coordinate positioned int he middle of the x-axis, and y at the middle of the y-axis. 现在,我想使用geom_text添加一个文本标签,该标签的x坐标位于x轴的中间,y位于y轴的中间。
It sounds like you just want something like 听起来你只是想要像
xx<-data.frame(
time=mean(range(example$time)),
value=mean(range(example$value))
)
ggplot(example, aes(x = time, y = value)) + geom_point() +
geom_text(data=xx, label="midtext") +
scale_x_date(labels = date_format("%b%Y"),
breaks = "3 month",
minor_breaks = "1 month")
We find the center of the plot by finding the center of the ranges of each of the axes. 我们通过找到每个轴范围的中心来找到图的中心。 Then we use theses values in the call to geom_text
. 然后,在对geom_text
的调用中使用这些值。
That will produce this picture. 那将产生这张照片。
PS. PS。 I also changed your date formatting line to 我也将您的日期格式行更改为
example$time <- as.Date(example$time, format = "%m/%d/%y")
since you only have two-digit years and not 4 digit years. 因为您只有两位数字的年份,而没有4位数字的年份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.