如何增加条形图日期的x轴刻度/标签频率?

4 投票
1 回答
2544 浏览
提问于 2025-04-18 15:34

我想在一个条形图上增加日期的刻度和标签的频率。现在它每隔两个月就显示一个标签,我想把这个频率改为每个月都显示一个标签。

我现在写的代码是:

fig = plt.figure()
ax = plt.subplot(1,1,1)

# defining the spacing around the plots
plt.subplots_adjust(left = 0.125, bottom = 0.1, right = 0.9, top = 0.9, wspace = 0.2, hspace = 0.35)

handles = []        # for bar plot  

bar1 = ax.bar(dates, clim[loc,:], label = 'climatology (1981 - 2013)', color='darkgray', width=width_arr[:], linewidth=0, alpha=0.5)

handles.append(bar1)

bar2 = ax.bar(dates, chirps[i,loc,:], label = str(year1), color = 'blue', width=width_arr[:], linewidth=0, alpha=0.45)
handles.append(bar2)


# setting the plot tick labels   
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(10)

for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontsize(10)

ax.set_ylabel("Precipitation", fontsize=10)

# plotting the legend within the plot space
plt.legend( loc = 'upper left', numpoints=1, ncol = 3, prop={'size':10})
plt.ylim(0, 110)

# rotating the tick marks to make best use of the x-axis space
plt.xticks(rotation = '25') 

1 个回答

3

你可以在 xticks 命令中指定 x 轴刻度的位置。所以在你的情况下,可以这样做:不要使用

plt.xticks(rotation = '25')  

而是使用

plt.xticks(dates,rotation = '25')

这里有一个 最简工作示例,可以帮助你理解问题和解决方法。

import numpy as np
import matplotlib.pyplot as plt

# generate random data
x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = np.random.rand(2,5)

# setup the plot
fig = plt.figure()
ax = plt.subplot(1,1,1)

# plot the data, only the bar command is important:
bar1 = ax.bar(x, y[0,:], color='darkgray', width=0.5, linewidth=0, alpha=0.5)
bar2 = ax.bar(x, y[1,:], color = 'blue', width=0.5, linewidth=0, alpha=0.45)

# defining the xticks
plt.xticks(rotation = '25')
#plt.xticks(x,rotation = '25')

plt.show()

这将生成以下图形:

question

在这个图中,我们看到的标签比我们希望的要多,这和你之前的情况正好相反,不过解决方法是一样的。
现在,如果你改变 plt.xticks 命令(在上面的例子中,你可以注释掉一行,取消注释另一行),图形将变成:

answer

y 轴的数据发生变化(因为调用了 np.random)并不重要。不过,你可以看到现在我们只有在 x 指定的位置上有 x 轴刻度。

如果你想跳过某些标签,我建议使用 numpy 的 arange 函数。与 linspace 不同,arange 允许你设置固定的增量(第三个输入参数)。你可以用下面的代码替换 plt.xticks(x,rotation='25') 行:

# defining the xticks
names = ['one', 'two', 'three', 'four', 'five']

x_tick_location = np.arange(np.min(x),np.max(x)+0.001,2.0)

x_tick_labels = [names[x.index(xi)] for xi in x_tick_location]

plt.xticks(x_tick_location,x_tick_labels,rotation = '25')

这将给你以下图形:

answer 2

有几点值得注意:

  • 我引入了一个列表 names,里面包含了作为刻度标签的字符串。我强烈建议不要这样设置标签,因为这会让你的刻度标签和数据脱节。不过在这里,它有助于说明 xticks 的工作原理。
  • 刻度位置是使用 np.arange 定义的,如上所述。在这个例子中,我们在 x 的最小值和最大值之间以 2 为增量。为了确保最大值能被考虑,可以稍微加一点(这和浮点数运算有关)。
  • 这个命令 [names[x.index(xi)] for xi in x_tick_location] 创建了一个列表,通过从 x_tick_location 中取每个元素,找到它在原始 x 中的索引,然后用这个索引选择 names 中对应的元素。
  • 最后,你将刻度位置和刻度标签都传递给 xticks 命令。

撰写回答