# 安装并加载ggplot2包
library(ggplot2)
# 创建数据集
set.seed(123) # 确保数据可重现
age = 1:30 # 年龄从1到30岁
height = 50 + (age^0.5) * 10 # 假设身高随年龄增长
weight = 3 + (age^0.5) * 2 # 假设体重随年龄增长
data = data.frame(age, height, weight)
# 绘制双坐标折线图
ggplot(data, aes(x=age)) +
geom_line(aes(y=height, colour="Height")) +
geom_line(aes(y=weight, colour="Weight")) +
geom_point(aes(y=height, colour="Height")) +
geom_point(aes(y=weight, colour="Weight")) +
scale_x_continuous(n.breaks = 15)+
scale_y_continuous(
n.breaks = 10,
name = "Height (cm)",
sec.axis = sec_axis(~ . , name="Weight (kg)",breaks = seq(0,100,by=10))) +
theme_bw()+
theme(text = element_text(family = "Calibri"))+
theme(legend.title = element_blank(),
legend.position = c(0,1), # 将图例放在顶部
legend.justification = c(0,1),
legend.background = element_blank()) # 设置图例背景透明
结果展示: