当 kind='bar' 时显示子图的标题,但当 kind='line' 时不显示

Titles of subplots are shown when kind='bar' but not when kind='line'

当我创建这样的子图时:

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

df = pd.DataFrame(np.random.randn(20, 10), columns=list('ABCDEFGHIJ'))

ax = df.plot(kind='bar', subplots=True, layout=(4, 3), sharex=True, sharey=False)

我得到这样的图,其中 headers 列用作子图的标题:

当我将kind='bar'更改为kind='line'时,只有图例而没有绘制标题。

解决方法是像这样使用 .get_legend_handles_labels()

for axi in itertools.chain.from_iterable(ax):
    try:
        axi.set_title(axi.get_legend_handles_labels()[1][0], {'size': 16})
    except:
        pass

然后给出正确的输出:

是否有更直接的方法来实现这一点?为什么 plot 根据标志 kind 表现不同?

解决方法:

  1. 获取当前development version of plotting.py。这允许向 plottitles 参数提供列表。
  2. 使用

    ax = df.plot(kind="line",subplots=True, layout=(4, 3), 
             sharex=True, sharey=False, title=list(df.columns.values))
    

    获取支线标题。

当然你也可以直接尝试更改代码以包含轴标题的设置。条形图的代码在当前开发版本的第 2006 行左右;并且您需要将它放置到 LinePlot 的 _make_plot() 方法中,位于行 1757 附近的某处,其中一个简单的 ax.set_title(label) 就足够了。问题可能是 pandas 会要求您重新构建它。 (我还没有测试过)。