用子图绘制pandas数据框(subplots = True):放置图例并使用紧密布局

Cor*_*yer 13 python matplotlib pandas

我非常喜欢处理和分析大数据集的熊猫.到目前为止,我主要使用matplotlib进行绘图,但现在想要使用pandas自己的绘图功能(基于matplotlib),因为它需要更少的代码,并且在大多数情况下似乎对我来说足够了.特别是在下面的例子中对大数据帧进行了一瞥的子图.

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

# Generate random data
df = pd.DataFrame(np.random.randn(96,12),
                  columns=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                           'K', 'L'])

# Plotting
df.plot(kind='line', subplots=True, grid=True, title="Sample Data (Unit)",
        layout=(4, 3), sharex=True, sharey=False, legend=True,    
        style=['r', 'r', 'r', 'g', 'g', 'g', 'b', 'b', 'b', 'r', 'r', 'r'],
        xticks=np.arange(0, len(df), 16))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

..我带来了我的问题:

1.)如何将所有图例放在子图中的同一位置(例如居中,外面,顶部)?

2.)我可以以某种方式使用matplotlibs"Tight Layout"(http://matplotlib.org/users/tight_layout_guide.html)作为情节吗?

提前致谢!

tmd*_*son 15

  1. 您可以将所有图例放在同一个位置,但您必须在单独的步骤中创建它们.

    # Plotting
    df.plot(kind='line', subplots=True, grid=True, title="Sample Data (Unit)",
        layout=(4, 3), sharex=True, sharey=False, legend=False,    
        style=['r', 'r', 'r', 'g', 'g', 'g', 'b', 'b', 'b', 'r', 'r', 'r'],
        xticks=np.arange(0, len(df), 16))
    
    [ax.legend(loc=1) for ax in plt.gcf().axes]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 当然.只是plt.tight_layout()在你show或之前使用savefig.比较使用和不使用下面创建的两个示例tight_layout.

没有tight_layout():

在此输入图像描述

tight_layout():

在此输入图像描述