python中多个对象的图例显示以及主次坐标轴设置

legend()的一个用法:

当我们有多个 axes时,我们如何把它们的图例放在一起呢??

我们可以这么做:

import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体为微软雅黑
# 定义房价
price = [10000, 12000, 16000, 14000, 13000, 19000]
# 定义成交量
total = [100, 50, 40, 60, 120, 40]
# 定义年份
year = [2010, 2011, 2012, 2013, 2014, 2015]
fig, ax = plt.subplots(1, 1)
# 共享x轴,生成次坐标轴
ax_sub = ax.twinx()
# 绘图
l1, = ax.plot(year, price, 'r-', label='price')    #注意这里是关键,l1后面多了一个',',这样才可以显示多个对象的图例
l2, = ax_sub.plot(year, total, 'g-', label='total')
# 放置图例
plt.legend(handles=[l1, l2], labels=['price', 'total'], loc=0)
# 设置主次y轴的title
ax.set_ylabel('房价(元)')
ax_sub.set_ylabel('成交量(套)')
# 设置x轴title
ax.set_xlabel('年份')
# 设置图片title
ax.set_title('主次坐标轴演示图')
plt.show()

在这里插入图片描述
在legend的参数中, loc参数设置图例的显示位置的:

best0
upper right1
upper left2
lower right4
lower left3
right5
center left6
center right7
lower center8
upper center9
center10
  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python ,可以使用 matplotlib 库来设置图多坐标轴,并设置坐标轴上的数字的字号。具体实现方法如下: 1. 导入 matplotlib 库: ```python import matplotlib.pyplot as plt ``` 2. 创建一个图像对象和两个子图: ```python fig, ax1 = plt.subplots() ax2 = ax1.twinx() ``` 3. 在 ax1 绘制需要显示在第一个坐标轴上的数据: ```python ax1.plot(x1, y1, 'r-', label='data1') ``` 4. 在 ax2 绘制需要显示在第二个坐标轴上的数据: ```python ax2.plot(x2, y2, 'b-', label='data2') ``` 5. 设置第一个坐标轴的标签和字号: ```python ax1.set_xlabel('X Label', fontsize=12) ax1.set_ylabel('Y1 Label', fontsize=12) ``` 6. 设置第二个坐标轴的标签和字号: ```python ax2.set_ylabel('Y2 Label', fontsize=12) ``` 完整示例代码: ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 x1 = np.linspace(0, 10, 100) y1 = np.sin(x1) x2 = np.linspace(0, 10, 100) y2 = np.exp(x2) # 创建图像对象和两个子图 fig, ax1 = plt.subplots() ax2 = ax1.twinx() # 在 ax1 绘制需要显示在第一个坐标轴上的数据 ax1.plot(x1, y1, 'r-', label='data1') # 在 ax2 绘制需要显示在第二个坐标轴上的数据 ax2.plot(x2, y2, 'b-', label='data2') # 设置第一个坐标轴的标签和字号 ax1.set_xlabel('X Label', fontsize=12) ax1.set_ylabel('Y1 Label', fontsize=12) # 设置第二个坐标轴的标签和字号 ax2.set_ylabel('Y2 Label', fontsize=12) # 显示图例 ax1.legend(loc='upper left') ax2.legend(loc='upper right') # 显示图像 plt.show() ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值