用Matplotlib在两个y轴上绘制多条直线

2024-06-11 09:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在两个y轴上绘制具有不同范围的多个特征。每个轴可能包含多个特征。下面的代码片段包括对象“Prin Balances”,它是一个包含按日期索引的数据类型float的df拖欠状态”是一个包含Prin余额列标题子集的列表。在

Delinquent_States = ['1 Mos','2 Mos','3 Mos','> 3 Mos']
fig, ax = plt.subplots()
plt.plot(Prin_Balances['UPB'], '--r', label='UPB')
plt.legend()
ax.tick_params('Bal', colors='r')

# Get second axis
ax2 = ax.twinx()
plt.plot(Prin_Balances[Delinquent_States],  label=Delinquent_States)
plt.legend()
ax.tick_params('vals', colors='b')

我的输出需要清理,尤其是图例。在

enter image description here

欢迎提出任何建议。在


Tags: plotplt特征paramsaxlabelbalancescolors
1条回答
网友
1楼 · 发布于 2024-06-11 09:47:40

简单到:

import pandas
import matplotlib.pyplot as plt
import random

# Generate some random data
df = pandas.DataFrame({'a': [random.uniform(0,0.05) for i in range(15)], 
                       'b': [random.uniform(0,0.05) for i in range(15)], 
                       'c': [random.uniform(0.8,1) for i in range(15)],
                       'd': [random.uniform(0.8, 1) for i in range(15)],
                       'e': [random.uniform(0.8, 1) for i in range(15)]})
plt.plot(df)

退货:

Plots

但我建议将它们分开绘制:

^{pr2}$

尖叫着:

enter image description here

添加:

可以为绘图的每一侧设置不同的比例:

fig, ax = plt.subplots()
plt.plot(df['a'], ' r', label='Line a')
plt.plot(df['b'], ' k', label='Line b')
plt.legend()
ax.tick_params('vals', colors='r')

# Get second axis
ax2 = ax.twinx()
plt.plot(df['c'], ' b', label='Line c')
plt.plot(df['d'], ' g', label='Line d')
plt.plot(df['e'], ' c', label='Line e')
plt.legend()
ax.tick_params('vals', colors='b')

不是最漂亮的,但你明白了。在

enter image description here

相关问题 更多 >