如何在条形图上增加日期的xticks /标签频率?

时间:2014-07-31 22:19:47

标签: python date matplotlib plot bar-chart

我正在尝试增加条形图上日期的xtick和标签频率。它目前每隔2个月贴一次标签,我想将其增加到每个月。

我到目前为止的代码是:

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 个答案:

答案 0 :(得分:3)

您可以在xticks命令中指定xtick loactions。因此,在你的情况下,这应该做的伎俩:而不是

plt.xticks(rotation = '25')  

使用

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

这是一个minimal working example,用于说明您的问题和解决方法。

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-ticks 。

如果您想跳过某些标签,我建议使用numpy's arange功能。与arange不同,linspace允许固定增量(第三个输入参数)。您可以使用以下代码替换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定义了刻度线位置。在min的{​​{1}}和max条目之间,我们在此示例中按x递增。向2值添加少量可能有助于确保可以考虑(这与浮点运算有关)。
  • 此命令max通过从[names[x.index(xi)] for xi in x_tick_location]获取每个元素,在原始x_tick_location中查找其索引并使用该索引选择x中的相应元素来创建列表。
  • 最后,您将勾选位置和刻度标签都传递给names命令。