繁体   English   中英

在 ggplot2 中绘制季节性时间序列

[英]Plotting seasonal time series in ggplot2

我想知道是否有人知道如何更好地绘制时间序列数据,其中 ggplot 对象上的 x 轴将是一个因子或字符分类对象。 下面是一个种群的例子,其中多样性在冬季降低并灭绝。 然后人口将在秋季增加。 有没有更好的方法来呈现这些数据? 任何建议,将不胜感激。

library(ggplot2)
library(data.table)

d <- rep(c(0, 10, 6, 0), 4)
time <- rep(c("Fall", "Fall", "Winter", "Winter"), 4)
year <- rep(1:4, each=4)
dt <- data.table(cbind(d, time, year))
dt$d <- as.numeric(dt$d)
dt$year <- as.numeric(dt$year)

ggplot(dt, aes(x=interaction(time, year), y=d, group=1)) +
  geom_line(position="identity", size=1) +
  geom_point(size=2)+
  labs(x="Year",
       y= "Diversity") +
  theme_classic()

具体来说,我想在每个冬天和秋天之间休息一下。 所以每个新年之间都有一个差距。

我会使用不同的方法 - 使用颜色来可视化每个冬季和秋季之间的中断( geom_rect ),将 x 轴转换为连续(从1到数据大小)。

使用 OP 数据:

library(ggplot2)
library(data.table)

# Prepare data
# Create continuous data for the x-axis
dt[, X := 1:.N]
# Define begging of the year
break_labels <- dt[, min(X), year]

# Plot
ggplot(dt, aes(X, d)) +
  # Use 0.5 to extend colour around the X
  geom_rect(aes(xmin = X - 0.5, xmax = X + 0.5, ymin = -Inf, ymax = Inf, fill = time)) +
  geom_point(size = 3) +
  geom_line(size = 1, linetype = 2) +
  # Specify wanted colour code
  scale_fill_manual(values = c("#EDBB99", "#D6EAF8")) +
  # Specify breaks only for the begging of the year
  scale_x_continuous(breaks = break_labels$V1, labels = break_labels$year) +
  labs(
    x = "Year",
    y = "Diversity",
    fill = "Season"
  ) +
  theme_classic()

在此处输入图片说明

编辑以展示如何使用两个不同的 y 变量。 请注意,在此解决方案中,零数据点直接位于测量数据点下方。 据我了解,您正在努力实现的目标是测量值时期和灭绝时期需要不同的时间点。

在行中创建中断的一种简单方法是用 NA 替换零。 根据您的用途,您可能希望将 y 轴延伸到零。 我更喜欢为此使用coord_cartesian 在第二张图中,我们改变 y 美学以使用完整的 d 列,从而得到零点来显示。

library(ggplot2)
library(data.table)

d <- rep(c(0, 10, 6, 0), 4)
time <- rep(c("Fall", "Fall", "Winter", "Winter"), 4)
year <- rep(1:4, each=4)
dt <- data.table(cbind(d, time, year))
dt$d <- as.numeric(dt$d)
dt$year <- as.numeric(dt$year)


# Plot with breaks in line, replace 0 with NA
dt <- dplyr::mutate(dt, d_na = ifelse(d == 0, NA, d))

ggplot(dt, aes(x=interaction(time, year), y=d_na, group=1)) +
  geom_line(position="identity", size=1) +
  geom_point(size=2)+
  labs(x="Year",
       y= "Diversity") +
  theme_classic() + 
  coord_cartesian(ylim = c(0,max(dt$d, na.rm = T)))

# Plot with zero points, use two different y variables
ggplot(dt, aes(x=interaction(time, year), y=d_na, group=1)) +
  geom_line(position="identity", size=1) +
  geom_point(aes(y = d), size=2)+
  labs(x="Year",
       y= "Diversity") +
  theme_classic() + 
  coord_cartesian(ylim = c(0,max(dt$d, na.rm = T)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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