jax
jax

Reputation: 840

Matplotlib float values on the axis instead of integers

I have the following code that shows the following plot. I can't get to show the fiscal year correctly on the x axis and it's showing as if they are float. I tried to do the astype(int) and it didn't work. Any ideas on what I am doing wrong?

p1 = plt.bar(list(asset['FISCAL_YEAR']),list(asset['TOTAL']),align='center')
plt.show()

This is the plot: enter image description here

Upvotes: 8

Views: 13211

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

In order to make sure only integer locations obtain a ticklabel, you may use a matplotlib.ticker.MultipleLocator with an integer number as argument.

To then format the numbers on the axes, you may use a matplotlib.ticker.StrMethodFormatter.

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

df = pd.DataFrame({"FISCAL_YEAR" : np.arange(2000,2017),
                   'TOTAL' : np.random.rand(17)})

plt.bar(df['FISCAL_YEAR'],df['TOTAL'],align='center')


locator = matplotlib.ticker.MultipleLocator(2)
plt.gca().xaxis.set_major_locator(locator)
formatter = matplotlib.ticker.StrMethodFormatter("{x:.0f}")
plt.gca().xaxis.set_major_formatter(formatter)
plt.show()

enter image description here

Upvotes: 15

Related Questions