matplotlib和pandas实现多y轴的多图形绘制

matplotlib和pandas实现多y轴的多图形绘制

我们知道pandas支持次Y轴,但是将三次Y轴或者多Y轴放置在绘图上的方法应该是怎么样的呢。效果图与代码实现如下。
 ![

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df =pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()

# df = pd.read_csv('d:\\pandas\\test.csv')
fig, ax = plt.subplots()
ax2, ax3 ,ax4 = ax.twinx(), ax.twinx() ,ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.125))
# ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.75)
rspine = ax4.spines['right']
rspine.set_position(('axes', 1.25))
ax4.patch.set_visible(False)

fig.subplots_adjust(right=0.75)
df.A.plot(ax=ax, style='b-',legend=False)
df.B.plot(ax=ax2,style='r-',legend=False)
df.C.plot(ax=ax3, style='g-',legend=False)
df.D.plot(ax=ax4, style='k-',legend=False)

#设置图例,如果没有这行代码会使图例重叠
ax4.legend([ax.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0],ax4.get_lines()[0]], ['A', 'B', 'C','D'],loc='best')


ax.set_xlabel("Time")
ax.set_ylabel('A',rotation=0)
ax2.set_ylabel('B',rotation=0)
ax3.set_ylabel('C',rotation=0)
ax4.set_ylabel('D',rotation=0)
ax.axhline(6, color="red", linestyle="--")
ax.axvline("2001-06-05", color="green", linestyle="--")

plt.title("test")

# 加这个两句 可以显示中文
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False

plt.show()
  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个完整的实例演示如何使用matplotlibpandas和xlwings从Excel文件中读取数据并绘制图表。 Excel数据: 日期 | 销售额 ----|----- 1/1/2021 | 100 1/2/2021 | 150 1/3/2021 | 200 1/4/2021 | 175 1/5/2021 | 250 1/6/2021 | 300 1/7/2021 | 225 步骤1:导入必要的库 ```python import pandas as pd import xlwings as xw import matplotlib.pyplot as plt ``` 步骤2:从Excel文件中读取数据 ```python # 打开Excel文件 wb = xw.Book('sales.xlsx') # 选择工作表 sht = wb.sheets['Sheet1'] # 读取数据 df = sht.range('A1:B8').options(pd.DataFrame, index=False, header=True).value ``` 步骤3:绘制图表 ```python # 设置图形大小和标题 plt.figure(figsize=(8,6)) plt.title('Sales') # 绘制折线图 plt.plot(df['日期'], df['销售额'], marker='o') # 设置x轴标签和旋转角度 plt.xticks(rotation=45) plt.xlabel('Date') # 设置y轴标签 plt.ylabel('Sales') # 显示图形 plt.show() ``` 完整代码: ```python import pandas as pd import xlwings as xw import matplotlib.pyplot as plt # 打开Excel文件 wb = xw.Book('sales.xlsx') # 选择工作表 sht = wb.sheets['Sheet1'] # 读取数据 df = sht.range('A1:B8').options(pd.DataFrame, index=False, header=True).value # 设置图形大小和标题 plt.figure(figsize=(8,6)) plt.title('Sales') # 绘制折线图 plt.plot(df['日期'], df['销售额'], marker='o') # 设置x轴标签和旋转角度 plt.xticks(rotation=45) plt.xlabel('Date') # 设置y轴标签 plt.ylabel('Sales') # 显示图形 plt.show() ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值