python - 使用 Matplotlib 在两个 y 轴上绘制多条线

标签 python matplotlib

我正在尝试绘制在两个 y 轴上具有不同范围的多个特征。每个轴可能包含多个特征。下面的代码片段包括对象“Prin Balances”,它是一个 df,其中包含按日期索引的数据类型 float。 “拖欠状态”是一个包含 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

欢迎提出任何建议。

最佳答案

简单如:

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

不过,我建议将它们分开绘制:

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

产生:

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

关于python - 使用 Matplotlib 在两个 y 轴上绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155510/

相关文章:

python - 消除 matplotlib 图中子图之间的空白

python matplotlib 热图颜色条从透明

python - 访问 Travis-CI 上的剪贴板

python - 如何找到之前列定义的每个子集中存在的 pandas 单元格值?

python - Cmd Windows "python"命令有效,但 "python3"无效,尽管我的 python 版本是 3.6

python - Matplotlib-Venn 中准确的颜色混合

python - 将数字添加到子图

python - 接受标量或 numpy 数组作为参数的 python 函数

python - 方法是否用类实例化,消耗大量内存(在 Scala 中)?

matplotlib - IPython 中的 python-ggplot 截断图中的图例