1

so, I'm stuck with two problem in formatting axis labels with matplotlib. I made a subplot of some x-y data changing axis labels. Actually those data are unix timestamp floating points which I use to make a linear fit. Then I formatted them in a more human readable way with time and datetime to use as labels for the plot. So far I'm successfull but...I have two problems:

  • first of all labels (both on x and y axis) are overlapping
  • Then on x axis, labels seems to be mooved to the right instead of matching the point's line (even if they are rotated)

This is a view of the plot:

![enter image description here

My code is the following:

def fit_one(x,y,lx,ly):
    par = np.polyfit(x, y, 1)
    q,m = np.polyfit(x, y, 1, cov=True)
    fit_fn=np.poly1d(par)
    fig, ax = plt.subplots(figsize=(15,15))
    
    ax.set_xticks(x)
    ax.set_xticklabels(lx, rotation=60)
    ax.set_yticks(y)
    ax.set_yticklabels(ly)
    ax.set_ylabel('gtu_time', fontsize = 12)
    ax.set_xlabel('entry_time',fontsize = 12)
    ax.plot(x,y,'k*',label='data')
    ax.plot(x,fit_fn(x),color='red', label='fit')
    #fig.tight_layout()

    fig.savefig('data_fit.pdf')
    #plt.xlim((1571512436,1609826672))
    plt.show()
    chi_squared = np.sum((np.polyval(par, x) - y) ** 2)
    print '\n\n'
    print 'Chi2   =    %.3f' % chi_squared  
    print 'p0     =    %.9f     +/- %.9f' % (q[1], np.sqrt(m[1][1]))
    print 'p1     =    %.9f     +/- %.9f' % (q[0], np.sqrt(m[0][0]))
    print '\n\n', par

Moreover I would like to understand why if I add loc='right' on the ax.set_xlabel('entry_time',fontsize = 12) line I get the following error:

AttributeError: Unknown property loc

which I really don't understand while it is on the matplotlib documentation.

Any advices on how to solve those problems? Thanks!

Mr. T
  • 11,960
  • 10
  • 32
  • 54
Gipsy
  • 61
  • 4
  • No problem on my end with `ax.set_xlabel('entry_time',fontsize = 12, loc="right")`. Matplotlib 3.3.3 Python 3.8 – Mr. T Jan 15 '21 at 15:39
  • As for their alignment, [see here](https://stackoverflow.com/q/14852821/8881141). They are aligned to their center. – Mr. T Jan 15 '21 at 15:44
  • 1
    There is no way to print all labels with the font size to the precise location without overlapping. you probably want to delete some label points (without deleting data points) – Bing Wang Jan 15 '21 at 15:49
  • 1
    `loc=` possibly doesn't work in older versions of matplotlib. You might want to upgrade to the latest. Also, Python 2 has been fully substituted to Python 3 nowadays. If possible, you really should upgrade. – JohanC Jan 15 '21 at 15:50

0 Answers0