在条形图中添加特定值的字母

Ayushi Nema

这是我的代码

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')
plt.xticks(np.arange(min(year), max(year) + 1, 5))

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

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

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

运行后,我得到了这样的情节: 在此处输入图片说明

我想在这里做两个改变。首先是:在 x 轴上,范围是 1975 年到 2018 年,我想在 x 轴上显示每年的标记,而不是年份。其次是:对于 x 的某些值;y 为零,因此对于零值,我想在 x 轴附近添加一个标签“G”。

请告诉有用的代码添加到这个程序。的数据是:1975 0.916 1976 0 1977 0 1978 1 1979 0.916 1980 0 1981 0 1982 0.75 1983 0.9 1984 1.125 1985 1.5 1986 0.416 1987 1 1988 0 1989 0 1990 1 1991 0 1992 0.4 1993 0.416 1994 0.7 1995 0.5 1996 0.571 1997 0.285 1998年1 1999年0.5 2000 0.545 2001年1 2002年0.333 2003 1.5 0.58 2004年2005年2006年0.454 0.375 0.444 2007年2008年2009年0 0 0 2010 2011 2012 2013年1 1 2014 1 2015年2 2016年2 2017年1.42

TC阿伦

要修改绘图刻度但每 5 年保留每个标签,您可以使用ax.set_xticks(..., minor=True). 接下来,您需要找出零值的位置并用于plt.text()在此特定位置设置标签。以下代码执行此操作:

plt.bar(year, relative_recurrence,color = 'grey', label = 'HILDCAAS', edgecolor='black')
plt.xticks(np.arange(min(year), max(year) + 1, 5))

ax = plt.gca()
ax.set_xticks(np.arange(min(year), max(year) + 1), minor=True)

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

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


# Find locations where relative_recurrence is 0
xlocs = np.where(np.array(relative_recurrence)==0)[0]
ylocs = np.zeros_like(xlocs) + 0.1

# Plot them in `data` coordinates. I.e. where x_values need to be in years.
xoffset = min(year) - 0.5
for idx in range(len(xlocs)):
    plt.text(xoffset + xlocs[idx], ylocs[idx], 'G')

这是它对我的看法:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章