Skip to content

plotting with index of objects should use FixedLocator #7612

Closed
@tacaswell

Description

@tacaswell

As pointed out here (https://stackoverflow.com/questions/24468333/set-xlim-for-pandas-matplotlib-where-index-is-string/24477138#24477138) if the index of a data frame is objects (that is not, the index obviously convertible to scalars and the data is being plotted against range(len(df))), the ticklabels are set to be string representations of the objects (I presume via set_xticklabels) but the locator is still a AutoLocator which means if you change the xlimits or pan/zoom the axes, the ticklabels become de-coupled from the data.

A solution is to also use a fixed locator which will pin the ticks to only be on the index locations.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

df = pd.DataFrame({'Foo': pd.Series([2,3,4], index=['2002', '2003', '2004'])})
fig, ax = plt.subplots()

df.plot(ax=ax)

ax.xaxis.set_major_locator(mticker.FixedLocator(np.arange(len(df))))
ax.xaxis.set_major_formatter(mticker.FixedFormatter(df.index))

I can make changes to the code if someone points me to where the relevant section is.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions