首先利用python爬取天气数据
预处理
在导入数据到 R 之前,先用 excel 在数据第一列前加一列 ID(可为连续的数字),作为 rownames。
R
# 线图绘制
setwd("D:/R learning")
library(ggplot2)
library(reshape2)
data = read.csv("i.csv", header = T, row.names = 1, sep = ",")
plot(rownames(data), data$最高气温..., type = "l")
ggplot 画图
ggplot(data, aes(x = ID, y = 最高气温...)) +
geom_point()
data2 = data[1:20, ]
data2$ID = factor(data2$ID, levels = data$ID)
# 不加 group = 1 会报错
ggplot(data2, aes(x = ID, y = 最高气温..., group = 1)) +
geom_line()
局部拟合
# 局部拟合
ggplot(data2, aes(x = ID, y = 最高气温..., group = 1, color = "最高温")) +
geom_line(size = 2) +
stat_smooth(method = "auto", se = FALSE, ) +
theme(legend.position = c(0.1,0.9))
多线图
# 多线图
data3 = data2[,1:3]
data_long = melt(data3, id.vars = "日期")
ggplot(data_long, aes(x = 日期, y = value, color = variable, group = variable)) +
geom_line(size = 1) +
stat_smooth(method = "auto", se = FALSE, ) +
theme(legend.position = c(0.85,0.16)) +
theme(axis.text.x = element_text(angle = 50, hjust = 1, vjust = 1, family = "serif")) +
theme(axis.title = element_text(family = "serif", size = 18)) +
theme(legend.text = element_text(family = "serif"))