1

I want to draw a plot in matplotlib that shows the temperature of August in 2016 and 2017. x-axis is time and y-axis is temparature. I try to stack 2 plots (one for 2016, one for 2017) on top of each other by sharing the x-axis that ranges from 2016-08-01 00:00:00 to 2016-08-31 23:00:00 and showing only the day of the month.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')

# times series from 2016-08-01 00:00:00 to 2016-08-31 23:00:00
x = stats_august_2016.MESS_DATUM
# temperature in 08.2016
y1 = stats_august_2016.TT_TU
# temperature in 08.2017
y2 = stats_august_2017.TT_TU

f, ax = plt.subplots()

# plot temp in 08.2016 
ax.plot(x, y1, 'yellow', label = '2016')
# plot temp in 08.2017 
ax.plot(x, y2, 'red', label = '2017')
# format x-axis to show only days of the month  
ax.xaxis.set_major_formatter(myFmt)
ax.grid(True)

plt.rcParams["figure.figsize"] = (12, 8)
plt.xlabel("Day of the Month", fontsize = 20, color = 'Blue')
plt.xticks(fontsize = 15)
plt.ylabel("Temperature ($\degree$C)", fontsize = 20, color = 'Blue')
plt.yticks(fontsize = 15)
ax.set_ylim(5, 35)
plt.title("Temperature in August 2016 and 2017", fontsize = 30, color = 'DarkBlue')
plt.legend(prop = {'size': 20}, frameon = True, fancybox = True, shadow = True, framealpha = 1, bbox_to_anchor=(1.22, 1))
plt.show()

Everything looks fine except the last tick of x-axis is somehow 2016-09-01 00:00:00. And the result looks odd with the 1 at the end.

enter image description here

How can I fix this?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Huy Tran
  • 1,770
  • 3
  • 21
  • 41

2 Answers2

1

The problem is, that your data is ranging until to some time late at the 31st of August of each year

# times series from 2016-08-01 00:00:00 to 2016-08-31 23:00:00

Matplotlib is then autoscaling the axis reaching up to the first day of the next month, displayed as a 1 in your chosen format. If you want to avoid this, you can set the x limit of the axis to the last timestamp of your data

ax.set_xlim([x[0], x[-1]])

The whitespace margin left and right of your axis will disappear then, though. If you want to keep this margin and still want to avoid the ticklabel of 1st of september, you can hide the last x-tick label with

xticks = ax.xaxis.get_major_ticks()
xticks[-1].label1.set_visible(False)
gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41
1

try:

ax.set_xlim(right=pd.Timestamp("2016-08-30 00:00:00"))

This will set the limit to day 30th.

Hamza
  • 255
  • 1
  • 4
  • 10