Home > other >  matplotlib: horizontal labels as style
matplotlib: horizontal labels as style

Time:01-15

Is there a parameter to force horizontal labels in an mplstyle file? and/or using rcParams?

I'm currently using ax.xaxis.set_tick_params(rotation=0) at plot construction. I'd like a permanent style or setting. Thanks!

Default look (with x_compat=True in a pandas dataframes):

enter image description here

Desired look:

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Date': {0: '1950-01-01', 1: '1960-01-02', 2: '1970-01-03', 3: '1980-01-04', 4: '1990-01-05'}, 'Value': {0 : 0, 1: 1, 2: 0, 3: 1, 4: 0}})
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df = df.set_index('Date', drop=False)

f, ax = plt.subplots()
df.plot(ax=ax, x='Date', x_compat=True)
#ax.xaxis.set_tick_params(rotation=0)
plt.show()

I looked in there, but may have missed it:

customizing-with-matplotlibrc-files

matplotlib_configuration_api.html

CodePudding user response:

Use parameter rot from df.plot

df.plot(ax=ax, x='Date', x_compat=True, rot=0)

CodePudding user response:

I'll answer my own question to put the matter to rest.

[as of January 2022] There is no way to control tick label rotation via a style. This is because the pandas plot wrapper resets the rotation parameter. To quote from pandas/doc/source/user_guide/visualization.rst,

pandas includes automatic tick resolution adjustment for regular frequency time-series data. For limited cases where pandas cannot infer the frequency information (e.g., in an externally created twinx), you can choose to suppress this behavior for alignment purposes. [...] Using the x_compat parameter, you can suppress this behavior

Despite the wording here --- namely "alignment purposes" ---, setting x_compat=True does not reset the rotation parameter back to its matplotlib default of 0, as I'd incorrectly expected.

There seem to be mainly two ways around this:

  1. Use matplotlib directly without pandas.
  2. Reset the rotation inside the pandas plot call. This may be done the pandas way [See Vishnudev's answer] with df.plot(... rot=0...) or the matplotlib way [See my OP] with an axis object setting ax.xaxis.set_tick_params(rotation=0).

Source and Thanks to: Jody Klymak in comments and Marco Gorelli at Github.

  •  Tags:  
  • Related