pandas matplotlib 调整大小和去除标签

1 投票
1 回答
3935 浏览
提问于 2025-04-17 22:01

我正在使用 pandas 和 matplotlib 来绘制数据框中的数据。我的做法是这样的:

df = pd.DataFrame({'type': dataFrame['Country'], labelName: 'Infant mort. rate'})
ax = df.plot(kind='bar',x= dataFrame['Country'])
ax.set_ylabel('Infant mort. rate')
ax.set_xlabel('Country')
plt.show()

在这里输入图片描述

我想去掉右上角的标签('color blue' 婴儿死亡率),并且我想调整整个窗口的大小,这样我就能看到 x 轴的标签(现在它被底部的白线挡住了)。我该怎么做呢?

1 个回答

3

首先,明确地创建你的图形和坐标轴对象,然后在调用 df.plot(...) 时传入一些额外的选项,最后在显示图形之前调用 fig.tight_layout()

import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots(figsize=(8,5))
df = pd.DataFrame({'type': dataFrame['Country'], labelName: 'Infant mort. rate'})
ax = df.plot(kind='bar', x=dataFrame['Country'], legend=False, ax=ax)
ax.set_ylabel('Infant mort. rate')
ax.set_xlabel('Country')
fig.tight_layout()
plt.show()

撰写回答