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

如何在Matplotlib柱状图中添加x轴年度刻度和y值为0处的'G'标签

Matplotlib柱状图修改实现

你需要对原有代码做两处调整,对应实现代码如下:

  • x轴刻度修改:删除原有plt.xticks(np.arange(min(year), max(year) + 1, 5))行,替换为以下代码:
# 固定x轴取值范围为1975年到2018年
plt.xlim(1975, 2018)
# 生成每一年的刻度线,隐藏所有刻度数值文本
plt.xticks(ticks=np.arange(1975, 2019, 1), labels=[""] * (2019 - 1975))
  • y=0点位添加G标签:在plt.bar()绘图语句后、plt.savefig()语句前添加以下代码:
# 遍历所有数据,在y值为0的点位添加G标签
for year_val, rr_val in zip(year, relative_recurrence):
    if rr_val == 0:
        # 0.02为标签距离x轴的高度,ha='center'保证标签与对应柱状图水平对齐
        plt.text(x=year_val, y=0.02, s="G", ha="center", fontsize=10)

完整修改后代码

import matplotlib.pyplot as plt
import numpy as np


# Declaring data
year = []
relative_recurrence = []

# Open data file
f = open('relative recurrence plot.txt','r')
for row in f:
    row = row.split(' ')
    year.append(int(row[0]))
    relative_recurrence.append(float(row[1]))
    
# Plot the graph    
plt.bar(year, relative_recurrence,color = 'grey', label = 'HILDCAAS', edgecolor='black')

# 新增:y=0点位添加G标签
for year_val, rr_val in zip(year, relative_recurrence):
    if rr_val == 0:
        plt.text(x=year_val, y=0.02, s="G", ha="center", fontsize=10)

# 替换原有xticks配置
# 固定x轴取值范围为1975年到2018年
plt.xlim(1975, 2018)
# 生成每一年的刻度线,隐藏所有刻度数值文本
plt.xticks(ticks=np.arange(1975, 2019, 1), labels=[""] * (2019 - 1975))

# Label for x-axis
plt.xlabel("YEAR")

# Label for y-axis
plt.ylabel("Relative Occurence")

plt.savefig('recurrence plot.png')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:54:03