gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:34:07 29 4
gpt4 key购买 nike

我想知道是否有人知道如何更好地绘制时间序列数据,其中 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()

enter image description here

关于r - 在 ggplot2 中绘制季节性时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201522/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com