pandas ,条形图设置自定义 [英] Pandas, Bar Chart Settings Customization

查看:101
本文介绍了 pandas ,条形图设置自定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了以下页面

  • http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html
  • http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.barh
  • http://matplotlib.org/users/customizing.html
  • http://matplotlib.org/users/configuration.html

但是自定义图形的详细设置仍然有困难.

But I'm still having difficulties customizing the detailed settings of my graph.

对于简单代码

#%matplotlib inline

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
plt.style.use('ggplot')

df = pd.DataFrame({
        'person':[x*16 for x in list('ABCDEF')],
        'score1':np.random.randn(6),
        'score2':np.random.randn(6),
        'score3':np.random.randn(6),
        'score4':np.random.randn(6),
        'score5':np.random.randn(6)
                   })
print(df)


plt.close('all')  # close all open figures
fig, ax = plt.subplots()

# X: pd.options.display.mpl_style = 'default' # cause system freeze
df.set_index(['person']).plot(kind='barh', ax = ax, width=0.85, fontsize=8)
ax.invert_yaxis()

plt.show()

结果如下:

也就是说,我的所有y标签都被剪掉了,页边距太大.我在这里找到了如何调整它们的方法:

I.e., all my y-labels are cut off, and margins are too big. I've found how to tweak them here:

但是我想知道如何以编程方式进行操作.

But I'm wondering how to do them programmatically.

谢谢

推荐答案

Matplotlib独立于图形对象创建轴子图对象.通常,您的子图无法正确地适合"您的图形,因此您将需要手动调整子图轴. Matplotlib现在有一个功能plt.tight_layout()尝试为您执行此操作.更多信息此处.

Matplotlib creates an axes subplot object independently from your figure object. Often your subplot will not be "fit" correctly on your figure and you will need to manually adjust your subplot axes. Matplotlib now has a function plt.tight_layout() that attempts to do this for you. More info here.

在显示绘图之前添加以下代码行应该为您完成

Adding the following line of code before displaying your plot should do it for you

plt.tight_layout()
plt.show()

另外,您应该查看此 SO答案,因为这是一个非常相似的问题.祝你好运!

Also you should look at this SO answer as this is a fairly similar question. Good luck!

这篇关于 pandas ,条形图设置自定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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