如何设置Matplotlib柱状图的顶部、右侧、底部及左侧坐标轴颜色
解决Matplotlib柱状图坐标轴边框的显示与颜色设置问题
需求说明
我已使用Python和Matplotlib成功创建柱状图,完成了柱子背景色、柱内数值颜色、x轴与y轴刻度标签颜色的设置。现需实现以下两项调整:
- 将顶部和右侧坐标轴边框设为隐藏
- 将底部(x轴)和左侧(y轴)坐标轴边框设为灰色
当前效果

目标效果

修改后的完整代码
# # File: bar.py # Version 1 # License: https://opensource.org/licenses/GPL-3.0 GNU Public License # import matplotlib import matplotlib.pyplot as plt def bar(category_labels: list = ["A", "B", "C", "D"], category_labels_color: str = "grey", data: list = [3, 8, 1, 10], bar_background_color: str = "red", bar_text_color: str = "white", direction: str = "vertical", x_labels_rotation: int = 0, figsize: tuple = (18, 5), file_path: str = ".", file_name: str = "bar.png"): """ Documentation: https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_label_demo.html """ # Debugging print(f"bar() :: data={data}") print(f"bar() :: category_labels={category_labels}") print(f"bar() :: bar_background_color={bar_background_color}") print(f"bar() :: bar_text_color={bar_text_color}") # Use agg matplotlib.use('Agg') # Draw bar fig, ax = plt.subplots(figsize=figsize) if direction == "vertical": bars = ax.bar(category_labels, data, color=bar_background_color) else: bars = ax.barh(category_labels, data, color=bar_background_color) # Add labels to bar ax.bar_label(bars, label_type='center', color=bar_text_color) # X and Y labels color + rotation plt.setp(ax.get_xticklabels(), fontsize=10, rotation=x_labels_rotation, color=category_labels_color) plt.setp(ax.get_yticklabels(), fontsize=10, color=category_labels_color) # 设置坐标轴边框样式:隐藏顶部、右侧,设置底部、左侧为灰色 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_color(category_labels_color) ax.spines['left'].set_color(category_labels_color) # Set grid color plt.rcParams.update({"axes.grid": False, "grid.color": "#cccccc"}) # Save figure plt.savefig(f"{file_path}/{file_name}", bbox_inches='tight', dpi=200) fig.clear() if __name__ == '__main__': category_labels = ['Dec 2022', 'Jan 2023', 'Feb 2023'] data = [34, 58, 7] bar_background_color= "#4f0176" bar_text_color = "white" category_labels_color = "grey" bar(category_labels=category_labels, data=data, bar_background_color=bar_background_color, bar_text_color=bar_text_color, category_labels_color=category_labels_color, file_path=f".", file_name="bar.png")
关键代码解释
Matplotlib中坐标轴边框由spines对象管理,每个方向(top/right/bottom/left)对应独立的边框实例:
ax.spines['top'].set_visible(False):隐藏顶部坐标轴边框ax.spines['right'].set_visible(False):隐藏右侧坐标轴边框ax.spines['bottom'].set_color(category_labels_color):将底部边框颜色设为与刻度标签一致的灰色ax.spines['left'].set_color(category_labels_color):将左侧边框颜色设为与刻度标签一致的灰色
将这段代码放在刻度标签设置之后、图片保存之前,即可实现目标效果。
内容的提问来源于stack exchange,提问作者Europa
相关产品推荐
相关产品推荐

