<think>我们使用R语言来绘制折线图。数据是时间序列,包含日期时间和对应的温度值。
步骤:
1. 创建数据框:将给定的数据输入到数据框中。
2. 转换日期时间格式:将时间列转换为POSIXct格式,以便正确排序和绘图。
3. 绘制折线图:使用ggplot2包来绘制折线图,或者使用基础绘图函数。
由于数据中包含的日期时间格式为“年/月/日 时:分”,我们将其转换为R中的日期时间类型。
注意:数据中存在跨天的时间,且时间点不连续。在绘制折线图时,我们需要确保时间轴的正确性。
我们将使用ggplot2来绘制,因为它可以更好地处理时间序列并美化图形。
如果没有安装ggplot2,需要先安装:install.packages("ggplot2")
以下是具体代码:
</think>
以下是使用R语言绘制折线图的完整解决方案,展示给定时间序列数据的温度变化:
```r
# 加载必要的包
library(ggplot2)
library(scales) # 用于时间轴格式化
# 创建数据框
temperature_data <- data.frame(
time = c(
"2025/11/17 2:00", "2025/11/17 6:00", "2025/11/17 10:00", "2025/11/17 14:00", "2025/11/17 18:00",
"2025/11/18 2:00", "2025/11/18 6:00", "2025/11/18 7:07", "2025/11/18 10:00", "2025/11/18 14:00", "2025/11/18 18:00", "2025/11/18 22:00",
"2025/11/19 2:00", "2025/11/19 6:00", "2025/11/19 10:00", "2025/11/19 14:00", "2025/11/19 18:00", "2025/11/19 22:00",
"2025/11/20 2:00", "2025/11/20 6:00", "2025/11/20 10:00", "2025/11/20 14:00", "2025/11/20 18:00",
"2025/11/21 6:00", "2025/11/21 10:00", "2025/11/21 14:00", "2025/11/21 18:00",
"2025/11/22 6:00", "2025/11/22 10:00", "2025/11/22 14:00", "2025/11/22 18:00",
"2025/11/23 6:00"
),
t = c(
37.7, 37.1, 39.0, 37.3, 38.4,
36.7, 38.4, 39.9, 36.8, 37.0, 39.1, 38.4,
38.4, 36.5, 37.9, 39.3, 38.1, 37.6,
36.8, 40.0, 36.5, 38.3, 37.8,
36.5, 37.2, 37.5, 36.5,
37.0, 37.2, 37.4, 37.0,
37.8
)
)
# 转换时间列为POSIXct格式
temperature_data$time <- as.POSIXct(temperature_data$time, format = "%Y/%m/%d %H:%M")
# 绘制折线图
ggplot(temperature_data, aes(x = time, y = t)) +
geom_line(color = "steelblue", linewidth = 1) + # 折线
geom_point(color = "red", size = 3) + # 数据点
labs(
title = "Time Series of Temperature (2025/11/17 - 2025/11/23)",
x = "Date and Time",
y = "Temperature (°C)",
caption = "Data recorded at irregular intervals"
) +
scale_x_datetime(
breaks = date_breaks("1 day"), # 每天一个主刻度
labels = date_format("%m/%d %H:%M"), # 日期格式化为月/日 时:分
minor_breaks = date_breaks("6 hours") # 每6小时一个次刻度
) +
scale_y_continuous(limits = c(36, 40)) + # 设置Y轴范围
theme_minimal() + # 简洁主题
theme(
plot.title = element_text(hjust = 0.5, face = "bold"), # 标题居中加粗
axis.text.x = element_text(angle = 45, hjust = 1), # X轴文本倾斜45度
panel.grid.major = element_line(color = "grey80"), # 主网格线
panel.grid.minor = element_line(color = "grey90") # 次网格线
)
```
### 代码解释:
1. **数据准备**:
- 创建包含两列(`time`和`t`)的数据框
- `time`列转换为POSIXct格式,确保R正确识别为时间序列数据
2. **绘图核心组件**:
- `geom_line()`:绘制蓝色折线连接所有数据点
- `geom_point()`:添加红色数据点标记每个测量值
- `scale_x_datetime()`:精细控制时间轴显示格式
- `scale_y_continuous()`:设置温度范围(36-40°C)
3. **图表美化**:
- 使用`theme_minimal()`简洁主题
- X轴标签旋转45度防止重叠
- 添加主/次网格线增强可读性
- 标题居中加粗,坐标轴标题清晰标注单位
### 图表特点:
- 自动处理不规则时间间隔的数据点
- 时间轴显示为"月/日 时:分"格式
- 每24小时显示一个主刻度,每6小时一个次刻度
- 红色数据点突显实际测量位置
- 自适应调整X轴标签避免重叠
执行代码将生成专业的时间序列折线图,清晰展示温度波动趋势,尤其突出显示11月20日6:00的40°C峰值点。