簡體   English   中英

在 rstudio 中使用 ggplot 繪制季度數據並指定季度

[英]Plot quarterly data and specify quarters using ggplot in rstudio

我想繪制季度數據,其中信息保存在變量 yq 中為:YYYY Q(例如 2007 Q1),我通過組合年份和季度(1、2、3、4)創建:

df$yq = as.yearqtr(paste(df$Year, df$Quarter), "%Y %q")

環顧網上的例子,我寫了這段代碼,但問題是它不允許我指定我想在 x 軸上顯示的年份 - 或者我似乎無法找到一種方法來應用休息時間這種類型的數據。 我有 15 年的數據,想每 3 年只顯示一次標簽,因此唯一的標簽是 2005.Q1、2008.Q1、2011.Q1、2014.Q1、2017.Q1。

感謝提示!

plot = ggplot(df, aes(x = yq, y = rate, color = "red")) +
  geom_point() +
  geom_line(aes(y = lin, color = "green"), size = 1) +
  geom_line(aes(y = quad, color = "brown"), size = 1) +
  geom_line(aes(y = cube, color = "blue"), size = 1) +
  geom_line(aes(y = log, color = "pink"), size = 1) +
  geom_line(aes(y = power_corr, color = "black"), size = 1) +
  geom_line(aes(y = exp_corr, color = "yellow"), size = 1) +
  scale_color_identity(name = "Models",
                       breaks = c("red", "green", "brown", "blue", "pink", "black", "yellow"),
                       labels = c("Observed", "Linear", "Quadratic", "Cubic", "Log", "Power", "Exponential"),
                       guide = "legend")

plot + 
theme(panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(), 
      panel.background = element_blank(), 
      axis.line = element_line(colour = "black"))+
  theme(axis.text.x = element_text(size = 8, angle=-45, hjust = 0.001), 
        legend.key = element_rect(color = NA, fill = NA))+
  labs(title="", x = "Year/quarters", y = "Smoking prevalence")+
  scale_x_yearqtr(format='%Y.Q%q')

未提供數據,因此我們將使用 x 和 y 向量的簡單示例,並使用帶有指定中斷和格式參數的 scale_x_yearqtr。

library(ggplot2)
library(zoo)

# inputs
x <- as.yearqtr(2000) + 0:29
y <- 1:30

qplot(x, y) + 
  scale_x_yearqtr(breaks = seq(min(x), max(x), by = 3), format = "%Y.Q%q")

暫無
暫無

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

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