Matplotlib浮点值在轴上而不是整数 [英] Matplotlib float values on the axis instead of integers

查看:287
本文介绍了Matplotlib浮点值在轴上而不是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码显示以下图表.我无法在x轴上正确显示会计年度,并且好像它们是浮动的.我试着做astype(int),但是没有用.关于我在做什么错的任何想法吗?

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()

这是情节:

推荐答案

为了确保只有整数位置才能获得刻度标签,可以使用带有整数的matplotlib.ticker.MultipleLocator作为参数.

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

要在轴上格式化数字,可以使用matplotlib.ticker.StrMethodFormatter.

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()

这篇关于Matplotlib浮点值在轴上而不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆