Pandas dataframe plot with subtitles (subplots = True): Place the legend and use a tight layout

I really like pandas to process and analyze large data sets. So far I have mainly used matplotlib to plot the graph, but now I want to use pandas own graph functions (based on matplotlib), since it requires less code and, apparently, is enough for me in most cases. Especially subtitles to take a look at large data frames, as in the following example.

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

enter image description here

.. which brings me to my questions:

1.) How to place all the legends in the subtitles in the same place (for example, in the center, outside, vertically)?

2.) - matplotlibs "Tight Layout" (http://matplotlib.org/users/tight_layout_guide.html) ?

!

+4
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]
    
  • . plt.tight_layout() show savefig. , tight_layout.

tight_layout():

enter image description here

tight_layout():

enter image description here

+7

Source: https://habr.com/ru/post/1617748/


All Articles