Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 786
jax Avatar asked Oct 17 '17 17:10

jax


People also ask

What does PLT axis (' equal ') do?

pyplot. axis() , it creates a square plot where the ranges for both axes occupy are equal to the length in plot.

Is PLT show () blocking?

show() and plt. draw() are unnecessary and / or blocking in one way or the other.

What does %Matplotlib mean in Python?

%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


1 Answers

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

like image 109
ImportanceOfBeingErnest Avatar answered Oct 05 '22 18:10

ImportanceOfBeingErnest