You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何增大Matplotlib柱状图刻度标签之间的间距以提升可读性

问题描述

我知道这个问题可能和本站其他问题重复,但我目前完全没有头绪。我现在的柱状图效果如下:
效果示意图
我想要增大刻度标签之间的间距,让标签内容可正常阅读。我尝试过很多找到的解决方案,但都没有生效,当前使用的代码如下:

import pandas as pd
import matplotlib.pyplot as plt


corr_df = pd.read_csv("country_corr_202112030124.csv")

fig, ax = plt.subplots(figsize=(40,3))

x = (range(corr_df['country_code'].size))
new_x = [2*i for i in x]

plt.bar(new_x,corr_df['temp_co2_corr_cof'], align='center', width=0.8)
plt.xticks([i*2 for i in range(corr_df['country_code'].size)], corr_df['country_code'])


# ax.set_xticks(corr_df['country_code'])
# ax.set_xticklabels(corr_df['country_code'], fontsize=8)
ax.set_xticklabels(corr_df['country_code'], rotation=90)

plt.show()

用到的csv数据可从公开数据集获取。

解决方案

你遇到的标签拥挤问题主要有两个核心原因:

  • 画布高度设置过小(仅3英寸),90度旋转后的纵向标签没有足够的垂直显示空间,导致大量重叠
  • 没有设置布局自适应,标签容易被画布边缘截断

修改后的可正常运行的代码如下:

import pandas as pd
import matplotlib.pyplot as plt


corr_df = pd.read_csv("country_corr_202112030124.csv")

# 调整画布高度,改为12英寸,可根据实际显示需求调整数值
fig, ax = plt.subplots(figsize=(40,12))

x = range(corr_df['country_code'].size)
# 如果需要进一步拉大柱子间距,可把系数2改为更大的数值,同步增大figsize的宽度参数即可
new_x = [2*i for i in x]

plt.bar(new_x, corr_df['temp_co2_corr_cof'], align='center', width=0.8)
plt.xticks([i*2 for i in range(corr_df['country_code'].size)], corr_df['country_code'])

# 可调整fontsize参数适配显示需求
ax.set_xticklabels(corr_df['country_code'], rotation=90, fontsize=10)
# 自动调整布局,避免标签被截断
plt.tight_layout()

plt.show()

内容的提问来源于stack exchange,提问作者KrishKhatri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:06:02