【R语言篇】ggplot绘制双坐标图

# 安装并加载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()) # 设置图例背景透明

结果展示:

  • 19
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值