Matplotlib showing x-tick labels overlapping

后端 未结 2 1631
自闭症患者
自闭症患者 2020-12-01 01:44

Have a look at the graph below: \"enter

It\'s a subplot of this larger figure:

2条回答
  •  孤街浪徒
    2020-12-01 02:41

    Due to the way text rendering is handled in matplotlib, auto-detecting overlapping text really slows things down. (The space that text takes up can't be accurately calculated until after it's been drawn.) For that reason, matplotlib doesn't try to do this automatically.

    Therefore, it's best to rotate long tick labels. Because dates most commonly have this problem, there's a figure method fig.autofmt_xdate() that will (among other things) rotate the tick labels to make them a bit more readable. (Note: If you're using a pandas plot method, it returns an axes object, so you'll need to use ax.figure.autofmt_xdate().)

    As a quick example:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    time = pd.date_range('01/01/2014', '4/01/2014', freq='H')
    values = np.random.normal(0, 1, time.size).cumsum()
    
    fig, ax = plt.subplots()
    ax.plot_date(time, values, marker='', linestyle='-')
    
    fig.autofmt_xdate()
    plt.show()
    

    If we were to leave fig.autofmt_xdate() out:

    enter image description here

    And if we use fig.autofmt_xdate():

    enter image description here

提交回复
热议问题