在 matplotlib 图中切割 X 和 Y 标签 [英] X and Y label being cut in matplotlib plots

查看:50
本文介绍了在 matplotlib 图中切割 X 和 Y 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
start = datetime.date(2016,1,1)
end = datetime.date.today()
stock = 'fb'
fig = plt.figure(dpi=1400)
data = web.DataReader(stock, 'yahoo', start, end)
fig, ax = plt.subplots(dpi=720)
data['vol_pct'] = data['Volume'].pct_change()
data.plot(y='vol_pct', ax = plt.gca(), title = 'this is the title \n second line')

ax.set(xlabel="Date")
ax.legend(loc='upper center', bbox_to_anchor=(0.32, -0.22), shadow=True, ncol=2)
plt.savefig('Test')

这是另一个代码的示例,但问题是相同的:

This is an example of another code but the problem is the same:

在图的底部,您可以看到图例已被剪切.在我正在处理的不同代码的另一个图中,当我使用 plt.savefig('Test') 保存图时,即使 ylabel 也被剪切.如何我可以解决这个问题吗?

At bottom of the plot you can see that the legend is being cut out. In another plot of a different code which i am working on, even the ylabel is also cut when i save the plot using plt.savefig('Test').How can i can fix this?

推荐答案

.savefig() 的一个长期问题是它在设置边界之前不检查图例和轴位置.通常,我用 bbox_inches 参数解决此问题:

It's a long-standing issue with .savefig() that it doesn't check legend and axis locations before setting bounds. As a rule, I solve this with the bbox_inches argument:

plt.savefig('Test', bbox_inches='tight')

这类似于调用 plt.tight_layout(),但考虑到所有相关的美术师,而 tight_layout 通常会在裁剪时将某些对象拉入框架新的.

This is similar to calling plt.tight_layout(), but takes all of the relevant artists into account, whereas tight_layout will often pull some objects into frame while cutting off new ones.

我必须告诉pyplot使其紧紧保持一半以上的时间,所以我不确定为什么这不是默认行为.

I have to tell pyplot to keep it tight more than half the time, so I'm not sure why this isn't the default behavior.

这篇关于在 matplotlib 图中切割 X 和 Y 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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