Fitting xtickslabels on a plot (matplotlib)

  • #1
95
2

Summary:

Fitting xtickslabels on plot

Main Question or Discussion Point

How could I improve the below code to fit all the xtickslabels on my plot more nicely (i.e. more spacing between the labels, higher resolution)? Thanks!

Python:
from pyplot import *
yearmonthday=['2003-01-01', '2003-02-01', '2003-03-01', ...] #len(yearmonthday) is 155
kwh = [88883, 99221, 100002, ...]
fig,ax=subplots(figsize=(9,2))
ax.plot(range(len(kwh)),kwh)
ax.set_xticks(range(len(yearmonthday)))
ax.set_xticklabels(yearmonthday, fontsize = 4,rotation=60)
ax.set_xlim(0,155,310)
fig.tight_layout()
ax.set_title('Energy consumption 2003-2015')
ax.set_ylabel('Kilowatthour')
plotx.png
 

Answers and Replies

  • #2
316
175
I propose to reduce the number of the ticks. You don't have to display a tick for each of the day, you can display only every second day for example, or every seventh day (if you prefer weekly basis).
Below I slightly updated your lines 6 and 7, in order to display a tick for every "step"-th day.

Python:
step = 7
ax.set_xticks(range(0, len(yearmonthday), step))
ax.set_xticklabels(yearmonthday[::step], fontsize=4, rotation=60)
 
  • Like
Likes schniefen and Ibix
  • #3
95
2
You're right, it's not necessary to display all dates. However, how would one make the title and the ylabel also fit into the figure? fig.tight_layout() fits the xtickslabels into the figure, but displaces the title and the ylabel somewhat outside of it.

Python:
fig,ax=subplots(figsize=(8,3))
ax.plot(range(len(kwh)),kwh)
step = 7
ax.set_xticks(range(0, len(yearmonthday), step))
ax.set_xticklabels(yearmonthday[::step], fontsize=10, rotation=60)
ax.set_xlim(0,155)
ax.set_yticks([100000,200000,300000])
ax.set_yticklabels(['$10^5$','$2 \cdot 10^5$','$3\cdot10^5$'], fontsize=10)
plt.tight_layout()
ax.set_title('Energy consumption 2003-2015')
ax.set_ylabel('Kilowatthour')
savefig('plotx.png',dpi=1200)
plotx.png
 
  • #4
316
175
Although I don't have your data, I tried to reproduce your code in jupyter notebook with %matplotlib inline option. And both, ylabel and title, look OK, not cropped as in your figure.
 
  • Like
Likes schniefen

Related Threads on Fitting xtickslabels on a plot (matplotlib)

Replies
1
Views
2K
Replies
1
Views
838
  • Last Post
Replies
1
Views
520
Replies
4
Views
12K
Replies
0
Views
2K
Replies
4
Views
833
Replies
6
Views
9K
  • Last Post
Replies
2
Views
2K
Top