Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在ggplot2中用年份注释第一个月_R_Ggplot2 - Fatal编程技术网

R 在ggplot2中用年份注释第一个月

R 在ggplot2中用年份注释第一个月,r,ggplot2,R,Ggplot2,假设我有这样一个情节: DF <- data.frame(date=Sys.Date() - (-100):100, y=rnorm(201)) library("ggplot2") library(scales) ggplot(DF, aes(x=date, y=y)) + geom_point() + scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%b")) DF您可以使

假设我有这样一个情节:

DF <- data.frame(date=Sys.Date() - (-100):100, y=rnorm(201))
library("ggplot2")
library(scales)
ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%b"))

DF您可以使用自定义日期格式化程序删除重复的年份:

my_date_format <- function()
{
   function(x)
   {
       m <- format(x,"%b")
       y <- format(x,"%Y")
       ifelse(duplicated(y),m,paste(m,y))
   }
}

ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=my_date_format())

my_date_格式不错!如果将函数更改为return
ifelse(复制(y),m,粘贴(m,y))
则可以避免月末名称的额外空格(这会导致它们在刻度线下不完全居中)。