簡體   English   中英

需要幫助在 x 軸 ggplot 圖上每 10 年顯示一次

[英]need help displaying every 10th year on x axis ggplot graph

在此處輸入圖像描述 需要幫助在 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")

以上是我當前的代碼,上圖顯示x軸很亂,看不到年份,我該如何解決?

如果這是您想要的 output,請閱讀以了解我所做的。

Output

ts_out

將數據另存為df

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

然后,使用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. 

准備在x-axis thenth year顯示一次的基數。 您可以使用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)
    )

最后是 plot 的后續層:

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM