简体   繁体   中英

Changing Date Labels From Odd to Even Years

I want to make a seemingly trivial adjustment to the chart pictured below:

I would like the labels along the x-axis to be even years, rather than odd years. So instead of going from 2009 -> 2011 -> 2013, they should go from 2008 -> 2010 -> 2012, and so forth...

How do I go about doing this?

Here is the code:

germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F)
italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F)

germany_yields <- germany_yields[, -(3:6)]
italy_yields <- italy_yields[, -(3:6)]

colnames(germany_yields)[1] <- "Date"
colnames(germany_yields)[2] <- "Germany.Yield"
colnames(italy_yields)[1] <- "Date"
colnames(italy_yields)[2] <- "Italy.Yield"

combined <- join(germany_yields, italy_yields, by = "Date")
combined <- na.omit(combined)
combined$Date <- as.Date(combined$Date,format = "%B %d, %Y")
combined["Spread"] <- combined$Italy.Yield - combined$Germany.Yield

fl_dates <- c(tail(combined$Date, n=1), head(combined$Date, n=1))

ggplot(data=combined, aes(x = Date, y = Spread)) + geom_line() +

       scale_x_date(limits = fl_dates, 
                    expand = c(0, 0), 
                    date_breaks = "2 years",
                    date_labels = "%Y")

A -- not very elegant -- way would be to put these arguments in your scale_x_date() :

scale_x_date(date_labels = "%Y", 
             breaks = ymd(unique(year(combined$fl_dates)[year(combined$fl_dates)%%2 == 0]), truncated = 2L)

(we define breaks manually, by subsetting the whole range of dates and keeping the even years)

That's actually fairly simple. Just set the lower limit to an even number, and set the upper limit to NA . As you haven't provided a reproducible example, here on some fake data.

library(tidyverse)

mydates <- seq(as.Date("2007/1/1"), by = "3 months", length.out =100)

df <- tibble(
  myvalue = rnorm(length(mydates))
)

# without limits argument

ggplot(df ) +
  aes(x = mydates, y = myvalue) +
  geom_line(size = 1L, colour = "#0c4c8a") +
  scale_x_date(date_breaks = "2 years",
               date_labels = "%Y")

# with limits argument 

ggplot(df ) +
  aes(x = mydates, y = myvalue) +
  geom_line(size = 1L, colour = "#0c4c8a") +
  scale_x_date(date_breaks = "2 years",
               date_labels = "%Y",
               limits = c(as.Date("2006/1/1"), NA))

Created on 2020-04-29 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM