0

Using Jupyter notebook matplotlib

I want to equally space the x tick marks, tick frequency (10), and rotate the labels (angle=45) on python matplotlib subplots.

Box 2 has the formatting closest to what I want but the ticks are not equally spaced. I can't get Box 1 x labels to rotate and the tick marks are not equally spaced.

ax1 = plt.xticks(rotation=45); --- does not rotate 45 instead it rotates ax2. I have also tried sharex=True in the plt.subplot callout

plt.style.use('ggplot');  
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,figsize=(14, 
4),sharex=False,sharey=True);
ax1.set_title('Box1', fontsize=17);
ax2.set_title('Box2', fontsize=17);
ax1.set_ylabel('Items', fontsize=15);

ax1.plot(item_1['var1'],linewidth=3,linestyle='solid',color='yellow');
ax1.plot(item_1['var1_inx'],linewidth=3,linestyle='dashed',color='yellow');
ax2.plot(item_1['var1_inx'],linewidth=3,linestyle='dashed',color='yellow');
ax2.plot(item_2['var1'],linewidth=3,linestyle='solid',color='yellow');
ax1.plot(item_1['var2'],linewidth=3,linestyle='solid',color='blue');
ax1.plot(item_1['var2_inx'],linewidth=3,linestyle='dashed',color='blue');
ax2.plot(item_1['var2_inx'],linewidth=3,linestyle='dashed',color='blue');
ax2.plot(item_2['var2'],linewidth=3,linestyle='solid',color='blue');
monthyearFmt = mdates.DateFormatter('%Y-%m');
ax1 = plt.xticks(rotation=45);
ax2.xaxis.set_major_formatter(monthyearFmt);

plt.show();

1:enter image description here

I added an image of the jupyter notebook. The red lines are what ticks to remove.

BenT
  • 3,172
  • 3
  • 18
  • 38
Paul
  • 113
  • 5
  • 20

2 Answers2

0

Calling plt.xticks(...) will apply those ticks to the most recently defined axes, ax2 in your case. To fix this, remove the assignment part from ax1 = plt.xticks(...) (this is assigning the labels themselves of ax2 to the variable ax1 which you don't want) and add the function call under a line where you draw onto the axes that you want. For example,

ax1.plot(item_1['var1'],linewidth=3,linestyle='solid',color='yellow')
plt.xticks(rotation=45)

xticks also takes in lists of ticks and corresponding labels as positional arguments if you want to use those.

Or, optionally, you can use set_xticks to affect a specific subplot.

Also, no need for semicolons in python :)

benrussell80
  • 297
  • 4
  • 10
0

Instead of plt.xticks use autofmt_xdate:

fig.autofmt_xdate(rotation=45)
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38