使用 Matplotlib 在两个 y 轴上绘制多条线 [英] Plotting mulitple lines on two y axis using Matplotlib
问题描述
我正在尝试绘制在两个 y 轴上具有不同范围的多个特征.每个轴可能包含多个特征.下面的代码片段包括对象Prin Balances",它是一个 df,其中包含按日期索引的数据类型浮点数.欠款状态"是一个列表,其中包含Prin天平的列标题的子集.
I am trying to plot multiple features which have different ranges on two y axis. Each axis might contain more than one feature. Code snippet below includes object "Prin Balances" which is a df which contains datatypes float indexed by dates. "Delinquent States" is a list containing a subset of the column headers of Prin Balances.
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')
我的输出需要清理,尤其是图例.
My output needs to be cleaned up, esp the legends.
欢迎提出任何建议.
推荐答案
就这么简单:
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)
返回:
我建议将它们分开绘制:
I would suggest however plotting them separately:
fig, ax = plt.subplots(nrows=2,ncols=1)
plt.subplot(2,1,1)
plt.plot(df['a'], 'r', label='Line a')
plt.legend()
plt.subplot(2,1,2)
plt.plot(df['b'], 'b', label='Line b')
plt.legend()
哪个产量:
已添加:
您可以为绘图的每一侧设置不同的比例:
You can set different scales for each side of the plot:
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')
不是最漂亮的,但是您明白了.
Not the prettiest, but you get the point.
这篇关于使用 Matplotlib 在两个 y 轴上绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!