【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)
相关推荐
ze言2 小时前
为什么现代 C++ (C++11 及以后) 推荐使用 constexpr和模板 (Templates) 作为宏 (#define) 的替代品?
开发语言·c++
Jinkxs3 小时前
高级15-Java构建工具:Maven vs Gradle深度对比
java·开发语言·maven
ccut 第一混3 小时前
c# winform 调用 海康威视工业相机(又全又细又简洁)
开发语言·c#·工业相机·海康威视
red润7 小时前
let obj = { foo: 1 };为什么Reflect.get(obj, ‘foo‘, { foo: 2 }); // 输出 1?
开发语言·javascript·ecmascript
froginwe117 小时前
PHP MySQL Delete 操作详解
开发语言
Nep&Preception7 小时前
vasp计算弹性常数
开发语言·python
DIY机器人工房8 小时前
一个基于 epoll 实现的多路复用 TCP 服务器程序,相比 select 和 poll 具有更高的效率
开发语言·嵌入式硬件·php·嵌入式·diy机器人工房
Ice__Cai8 小时前
Python 基础详解:数据类型(Data Types)—— 程序的“数据基石”
开发语言·后端·python·数据类型
lilv669 小时前
python中用xlrd、xlwt读取和写入Excel中的日期值
开发语言·python·excel