需要帮助在 x 轴 ggplot 图表上显示每 10 年

1 r ggplot2

在此输入图像描述需要帮助在 x 轴上每 10 年绘制一次。

temp_carbon %>%
  select(Year = year, Global = temp_anomaly, Land = land_anomaly, Ocean = ocean_anomaly) %>%
  gather(Region, Temp_anomaly, Global:Ocean) %>%
  drop_na() %>% 
  ggplot(aes(Year, Temp_anomaly, col = Region)) +
  geom_line(size = 1) +
  geom_hline(aes(yintercept = 0), lty = 2) +
  geom_label(aes(x = 2005, y = -.08),label = "20th century mean", size = 4) +
  ylab("Temperature anomaly (degrees C)") +
  scale_x_continuous(breaks = function(x) exec(seq, !!!x), 
                     labels = function(x) x, 
                     limits = c(1880, 2018)) +
  ggtitle("Global, Land and Ocean Temperatures from 1880-2018")
Run Code Online (Sandbox Code Playgroud)

上面是我当前的代码,上图显示x轴非常混乱,看不到年份,我该如何解决这个问题?

dee*_*fan 5

如果这是您想要的输出,请阅读以了解我所做的事情。

输出

ts_输出

将您的数据另存为df

df <- temp_carbon %>%
  select(Year = year, Global = temp_anomaly, Land = land_anomaly, Ocean = ocean_anomaly) %>%
  gather(Region, Temp_anomaly, Global:Ocean) %>%
  drop_na()
Run Code Online (Sandbox Code Playgroud)

然后,使用lubridate将其转换为正确的日期

df$Year <- lubridate::ymd(df$Year, truncated = 2L)
# [1] "1880-01-01" "1881-01-01" "1882-01-01" "1883-01-01" "1884-01-01" "1885-01-01"
# This sets the month and date on Jan-01. 
Run Code Online (Sandbox Code Playgroud)

准备好显示每一个的thenth year底座x-axis。您可以使用每十年计算一次seq(min(year(df$Year)), max(year(df$Year)), by = 10)

base <- ggplot(df, aes(year(Year), Temp_anomaly, col = Region)) + 
    theme(axis.text.x = element_text(angle = 90, size = 7, vjust =0.5, margin=margin(5,0,0,0))) +
    scale_x_continuous(
        "Year", 
        labels = as.character(seq(min(year(df$Year)), max(year(df$Year)), by = 10)), 
        breaks = seq(min(year(df$Year)), max(year(df$Year)), by = 10), 
        expand=c(0,0)
    )

Run Code Online (Sandbox Code Playgroud)

最后是情节的后续层:

base + geom_line(size = 1) +
  geom_hline(aes(yintercept = 0), lty = 2) +
  geom_label(aes(x = 2005, y = -.08),label = "20th century mean", size = 4) +
  ylab("Temperature anomaly (degrees C)") + 
  ggtitle("Global, Land and Ocean Temperatures from 1880-2018")
Run Code Online (Sandbox Code Playgroud)