# 读取数据
data <- read_excel("E:\\论文2\\数据2025\\PM2.5\\气象归一PM2.5.xlsx")
# 选择要绘制的列
cols_to_plot <- c("date", "4", "5", "6", "40", "79", "84", "92", "95", "99", "101", "107", "108", "109", "115", "116", "134", "144", "151", "166", "175", "179")
data_selected <- data[, cols_to_plot]
# 检查并转换日期格式(确保date列为日期类型)
if (!inherits(data_selected$date, "Date")) {
data_selected$date <- as.Date(data_selected$date) # 若日期格式错误,需根据实际格式调整,如:as.Date(data$date, format = "%Y-%m-%d")
}
# 将需要绘制的列转换为数值类型
for (col in cols_to_plot[-1]) {
data_selected[[col]] <- as.numeric(data_selected[[col]])
}
# 将数据转换为长格式,以便每一列都能绘制在一张图中
data_long <- data_selected %>%
pivot_longer(cols = -date, names_to = "variable", values_to = "value")
# 自定义颜色调色板
my_palette <- hue_pal()(n_distinct(data_long$variable))
# 定义图例顺序
legend_order <- c("4", "5", "6", "40", "79", "84", "92", "95", "99", "101", "107", "108", "109", "115", "116", "134", "144", "151", "166", "175", "179")
# 使用ggplot进行绘图
p <- ggplot(data_long, aes(x = date, y = value, color = variable, group = variable)) +
geom_line(linewidth = 0.8) +
scale_color_manual(
values = setNames(my_palette, legend_order),
labels = legend_order,
name = "" # 清空图例名称
) +
labs(
x = "日期",
y = expression("PM"[2.5]~" ("*mu*"g m"^-3*")") # 将10设为下标
) +
theme_bw() +
theme(
legend.position = c(0.8, 0.95), # 将图例置于图形内顶部中间位置
legend.justification = c(0.8, 1), # 图例水平居中,垂直顶部对齐
legend.title = element_blank(),
legend.background = element_rect(fill = "white", color = "grey50"),
legend.margin = margin(2, 4, 2, 4),
legend.key.size = unit(0.4, "cm"), # 进一步减小图例图标大小
legend.text = element_text(size = 7), # 进一步减小图例文字大小
axis.title = element_text(size = 16.5),
plot.margin = unit(c(1,1,2,1), "cm"),
axis.text.x = element_text(angle = 0, hjust = 1),
panel.spacing = unit(0.3, "cm"),
axis.title.x = element_text(hjust = 0.5, size = 15) # 将日期标签放在中间
) +
guides(color = guide_legend(nrow = 7)) # 设置为三行显示
print(p)
ggplot2::ggsave(
filename = "E:\\论文2\\图\\1PM2.5气象归一.tiff", # 学术论文推荐TIFF格式
width = 15, # 根据期刊要求调整
height = 8, # 单位默认英寸
dpi = 600, # 多数期刊接受300-600dpi
compression = "lzw" # TIFF压缩选项
)这个的图片设置与上面设置一样
最新发布