hhprogram
hhprogram

Reputation: 3147

Matplotlib newline character in xtick label

I've seen a bunch of solutions (including matplotlib example code) that to have an x-tick label be multi-line you can just introduce a newline character. Which I did (below is a code excerpt that adds this newline):

subplot.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d\n%H:%M", tz=startTime.tzinfo))

However, I noticed this introduces a weird quirk in which when I mouse-over the plots it kind of causes all the plots to 'jump' up and down (shift slightly up and then back down when I mouse over again). Note: if there is just one plot then the bottom matplotlib toolbar (with the save button etc..) shifts up and down only. This makes it unpleasant to look at when you are trying to move the mouse around and interact with the plots. I noticed when I take out the new-line character this quirk disappears. Anyone else run into this and solve it (as in keeping multiline label without this weird 'jump' quirk)?

I'm using Python 3.6 and matplotlib 1.5.3. using TKAgg backend.

Upvotes: 1

Views: 4067

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339570

By default, the same formatter is used for the values shown in the NavigationToolbar as on the axes. I suppose that you want to use the format "%m-%d\n%H:%M" in question just for the ticklabel formatting and are happy to use a single-line format for the values shown when moving the mouse.

This can be achieved by using a different formatter for those two cases.

# Format tick labels
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d\n%H:%M"))
# Format toolbar coordinates
ax.fmt_xdata = mdates.DateFormatter('%m-%d %H:%M')

Example picture:

Complete code for reproduction:

import matplotlib
matplotlib.use("TkAgg")
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

dates = pd.date_range("2016-06-01 09:00", "2016-06-01 16:00", freq="H" )

y = np.cumsum(np.random.normal(size=len(dates)))
df = pd.DataFrame({"Dates" : dates, "y": y})

fig, ax = plt.subplots()
ax.plot_date(df["Dates"], df.y, '-')

ax.xaxis.set_major_locator(mdates.HourLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d\n%H:%M"))

ax.fmt_xdata = mdates.DateFormatter('%m-%d %H:%M')

plt.show()

Upvotes: 4

Related Questions