Python画图-主次坐标轴和翻转坐标轴

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kabuto_hui/article/details/86591532


  很多时候我们在进可视化的时候希望把两个不同量纲的数据绘在一张图中。比如我们希望在一张图中画出历年房子的成交量和价格变化趋势图,或者是降雨与水位的变化趋势图等。这些量纲不一样就需要用到主次坐标轴来实现。

1. 主次坐标轴

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')
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()

我随便定义了一些数据,其中最为主要的就是通过语句:ax_sub = ax.twinx()实现共享x轴,其实就是实现了主次坐标轴,这样我们就拿到了主次坐标轴的句柄,通过句柄来实现我们想画出的任何图片;

在上图中,我们把房价和成交量都以折现图的形式画出来了,同时我们也可以画柱状图和折线图并存,比如我们将成交量化成柱状图,那么我们在上面的代码中只需将画图部分修改为:

fig, ax = plt.subplots(1, 1)
# 共享x轴,生成次坐标轴
ax_sub = ax.twinx()
# 绘图
ax_sub.plot(year, price, 'r-', label='price')
ax.bar(year, total)
# 放置图例
plt.legend(loc=0)
# 设置主次y轴的title
ax_sub.set_ylabel('房价(元)')
ax.set_ylabel('成交量(套)')
# 设置x轴title
ax.set_xlabel('年份')
# 设置图片title
ax.set_title('主次坐标轴演示图')
plt.show()

就可以得到如下的图:

可以看到我们已经成功的实现了柱状图和折现图同时出现在一张图中的功能了,这其实就是利用了主次坐标轴的性质而已。

需要注意的是:次坐标轴画的图会出现在图的顶层。

所以我将折线图用次坐标轴ax_sub来画的,不然折现会被柱状图覆盖!

2. 翻转坐标轴

  有时候我们在画出主次坐标轴之后,希望有一个曲线是倒着的,这样可以更加直观的观察数据的变化趋势。要实现这个功能只需要反转坐标轴即可。这里有两种办法:
1. 通过语句ax.invert_yaxis()来实现:

fig, ax = plt.subplots(1, 1)
# 共享x轴,生成次坐标轴
ax_sub = ax.twinx()
# 绘图
ax_sub.plot(year, total, 'r-', label='total')
ax.bar(year, price)

# 翻转房价的坐标轴
ax.invert_yaxis()

# 放置图例
plt.legend(loc=0)
# 设置主次y轴的title
ax.set_ylabel('房价(元)')
ax_sub.set_ylabel('成交量(套)')
# 设置x轴title
ax.set_xlabel('年份')
# 设置图片title
ax.set_title('主次坐标轴演示图')
plt.show()

2. 通过ax.set_ylim()来实现:

fig, ax = plt.subplots(1, 1)
# 共享x轴,生成次坐标轴
ax_sub = ax.twinx()
# 绘图
# l1, = ax.plot(year, price, 'r-', label='price')
l2, = ax_sub.plot(year, total, 'r-', label='total')
ax.bar(year, price)


# 翻转房价的坐标轴
ax.set_ylim((30000, 0))

# 放置图例
# plt.legend(handles=[l1, l2], labels=['price', 'total'], loc=0)
plt.legend(loc=0)
# 设置主次y轴的title
ax.set_ylabel('房价(元)')
ax_sub.set_ylabel('成交量(套)')
# 设置x轴title
ax.set_xlabel('年份')
# 设置图片title
ax.set_title('主次坐标轴演示图')
plt.show()

通过手动设置房价的坐标轴是从30000~0就实现了坐标轴的反转,同时还实现了图的缩放:

猜你喜欢

转载自blog.csdn.net/kabuto_hui/article/details/86591532