pandas - 如何在 Pyplot 中禁用 x_axis 标签?
问题描述
我可以知道如何禁用 Pyplot 中的 x 轴标签吗?或者,如何调整图表之间的间距?
fig, axes = plt.subplots(nrows=3,figsize=(30,20))
df1.pivot('date','symbol','roe').plot(kind='bar', ax=axes[0]).set_title('ROE', fontsize=20)
df1.pivot('date','symbol','roa').plot(kind='bar', ax=axes[1]).set_title('ROA')
df1.pivot('date','symbol','eps').plot(kind='bar', ax=axes[2]).set_title('EPS')
解决方案
大熊猫的解决方案
使用pandas 绘图功能时,您可以通过设置删除 x 轴标签xlabel=''
。您可以在创建第一个绘图后使用以下方法另外删除 x 轴刻度线和刻度标签,例如axes[0].xaxis.set_visible(False)
:
gridspec_kw=dict(hspace=0.3)
您可以通过添加到plt.subplots
函数调用来调整子图之间的垂直空间。最后,您还可以在创建第一个图后使用以下方法调整标题和子图之间的间距,例如:axes[0].set_title('ROE', pad=5)
.
为了说明这一点,让我首先创建一个类似于您的可重现的示例数据集:
import numpy as np # v 1.19.2
import pandas as pd # v 1.1.3
import matplotlib.pyplot as plt # v 3.3.2
# Create sample dataset stored as a pandas dataframe
rng = np.random.default_rng(seed=1) # random number generator
years = np.arange(2013, 2020)
symbols = np.array(list('ABCD'))
df = pd.DataFrame(10+rng.integers(-5, 6, size=(symbols.size*years.size, 3)),
columns=['roe', 'roa', 'eps'])
df['symbol'] = np.repeat(symbols, years.size)
df['date'] = symbols.size*list(years)
df.head()
# roe roa eps symbol date
# 0 10 10 13 A 2013
# 1 15 5 6 A 2014
# 2 14 15 7 A 2015
# 3 8 14 9 A 2016
# 4 8 14 7 A 2017
我建议在一次绘制多个变量时使用 for 循环从数据框中绘制所需的变量。这使您可以一次性格式化所有子图。在以下示例中,我从所有三个子图中删除了 x 轴和图例,然后仅将它们添加回我想要的位置:
# Create figure with space between subplots: note that sharex=True is not needed
fig, axs = plt.subplots(3, 1, gridspec_kw=dict(hspace=0.3), figsize=(9, 7))
# Loop through axes to plot bar charts with titles but no x labels, x ticks or legends
for ax, var in zip(axs.flat, ['roe', 'roa', 'eps']):
df.pivot('date','symbol').plot.bar(y=var, ax=ax, xlabel='', rot=0)
ax.set_title(var.upper(), pad=5)
ax.xaxis.set_visible(False) # remove this and add sharex=True for tick marks only
ax.legend().remove()
# Add x-axis ticks and tick labels to last subplot and add legend
axs[-1].xaxis.set_visible(True)
axs[1].legend(loc=(1.05, 0.25), frameon=False);
seaborn 解决方案
seaborn 包旨在以一种方便的方式生成这种类型的图形,这就是为什么值得添加一个使用 seaborn 的示例,使用与上面相同的数据创建,这次保留默认的刻度线。必须首先重新调整数据框的形状,以使要绘制的三个变量包含在单个列中。请注意,seaborn 的唯一缺点是您无法轻松更改条形的宽度。您可以参考下面链接的文档以获取更多详细信息和示例。
import seaborn as sns # v 0.11.0
df_sns = df.melt(id_vars=['date', 'symbol'])
df_sns.head()
# date symbol variable value
# 0 2013 A roe 10
# 1 2014 A roe 15
# 2 2015 A roe 14
# 3 2016 A roe 8
# 4 2017 A roe 8
g = sns.catplot(kind='bar', data=df_sns, x='date', y='value', hue='symbol',
row='variable', height=2, aspect=3.5, saturation=1)
g.fig.subplots_adjust(hspace=0.3)
g.set_axis_labels(x_var='', y_var='')
for ax, var in zip(g.axes.flat, g.row_names):
ax.set_title(var.upper(), pad=5)
推荐阅读
- python - 使用 Python Flask 将文件上传到 IBM COS
- json - 无法在 Swift 中展开和折叠 TableViewCell
- angular - 根据angularJS v1.4.8中的值隐藏剑道网格列
- asp.net-core - 如何在 GraphQL .Net Core 中进行授权?
- javascript - 如何在 ChartJS 中插入标签而不重新缩放其他标签?
- python - 搜索和拆分列表
- amazon-web-services - 录制 wav 并将其上传到 Amazon S3
- python - 为 R 安装库并遇到“Rcpp”问题
- jenkins - jenkins 无法拉取分叉存储库上的提交
- python - 高效计算共现矩阵