【问题标题】:Add alphabet at specific value in bar graph在条形图中以特定值添加字母
【发布时间】:2021-10-30 01:21:15
【问题描述】:

这是我的代码

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 2004 年 0.58 2005 年 0.454 2006 年 0.375 2007 年 0.444 2008 0 2009 0 2010 0 2011 2 2012 1 2013 1 2014 1 2015 2 2016 2 2017 1.42

【问题讨论】:

  • 非常感谢!!!!我对此持负面看法。所以我把它删了。

标签: python pandas numpy matplotlib


【解决方案1】:

要修改绘图刻度但每 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')

这就是我的样子:

【讨论】:

  • 希望我添加的数据对你有帮助
  • 谢谢。请查看编辑。我最初的 plt.xticks() 不正确,我添加了 G 的绘图。
  • 谢谢。代码有效。但是第一个查询仍未解决(也许我不清楚)。我想让刻度可见,但要以 5 步长显示年份。
  • 好吧,我误解了第一个查询。我编辑了我的答案来完成这个。我觉得应该够了
猜你喜欢
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多