【R语言编程绘图-折线图】

安装与加载GGPLOT2库

确保已安装ggplot2库,若未安装可通过以下命令安装:

r 复制代码
install.packages("ggplot2")

加载库:

r 复制代码
library(ggplot2)

准备数据

假设有一个包含时间序列数据的数据框df,包含两列:date(日期)和value(数值)。示例数据生成:

r 复制代码
df <- data.frame(
  date = seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "month"),
  value = c(15, 18, 22, 25, 30, 28, 26, 24, 20, 18, 16, 14)
)

基础折线图绘制

使用geom_line()绘制折线图:

r 复制代码
ggplot(df, aes(x = date, y = value)) +
  geom_line()

自定义折线图样式

调整线条颜色、粗细和添加点标记:

r 复制代码
ggplot(df, aes(x = date, y = value)) +
  geom_line(color = "blue", linewidth = 1) +
  geom_point(color = "red", size = 3)

添加标题与坐标轴标签

通过labs()函数设置标题和标签:

r 复制代码
ggplot(df, aes(x = date, y = value)) +
  geom_line(color = "blue") +
  labs(title = "Monthly Value Trends (2023)",
       x = "Date",
       y = "Value")

调整坐标轴格式

例如将日期格式化为月份缩写:

r 复制代码
ggplot(df, aes(x = date, y = value)) +
  geom_line(color = "blue") +
  scale_x_date(date_labels = "%b") +
  labs(title = "Monthly Trends", x = "Month", y = "Value")

多系列折线图

若数据包含分组(如category列),可通过aes(color)区分不同系列:

r 复制代码
df_multi <- data.frame(
  date = rep(seq(as.Date("2023-01-01"), as.Date("2023-06-01"), by = "month"), 2),
  value = c(15, 18, 22, 25, 30, 28, 10, 12, 15, 18, 20, 22),
  category = rep(c("A", "B"), each = 6)
)

ggplot(df_multi, aes(x = date, y = value, color = category)) +
  geom_line() +
  labs(title = "Multi-Series Line Chart")
复制代码
# 加载必要的库
library(ggplot2)

# 生成数据
df <- data.frame(
  date = seq(as.Date("2023-01-01"), by = "day", length.out = 100),
  value = cumsum(rnorm(100))
)

# 绘制折线图
p <- ggplot(df, aes(x = date, y = value)) +
  geom_line(color = "blue", size = 1) +  # 使用蓝色线条,适当调整线条粗细
  labs(title = "Time Series Plot of Random Values",  # 标题
       x = "Date",  # X轴标签
       y = "Cumulative Sum of Random Values") +  # Y轴标签
  theme_classic() +  # 使用经典主题
  theme(plot.title = element_text(size = 16, face = "bold", hjust = 0.5),  # 标题样式
        axis.title = element_text(size = 14, face = "bold"),  # 轴标题样式
        axis.text = element_text(size = 12),  # 轴刻度标签样式
        legend.position = "none")  # 移除图例(如果不需要)

# 保存为高分辨率图像
ggsave("time_series_plot.png", plot = p, width = 8, height = 6, dpi = 300)

# 显示图像
print(p)
相关推荐
丰锋ff14 小时前
基于 Qt 的智能门禁系统(二)
开发语言·qt
fpcc14 小时前
跟我学C++中级篇——编译期的条件选择
开发语言·c++
SomeB1oody14 小时前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
mqiqe15 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim15 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
脉动数据行情15 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
爱学习的小邓同学15 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
zx_7414848116 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python
liangshanbo121518 小时前
虚拟列表深度面试题整理
java·开发语言·前端
ZISHU_98718 小时前
用 TLabel 给 SynTouch BioTac 数据做语义标注:从原始信号到结构化标注
开发语言·人工智能·python·数据·机器人触觉