How to increase the frequency of xticks / labels for dates on a chart?

I am trying to increase the frequency of labels and date labels on a barplot. Currently, he puts labels on every second month, and I would like to increase it to every month.

The code I have so far is:

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') 
+4
source share
1 answer

You can specify xtick loactions in a command xticks. So in your case, this should do the trick: instead

plt.xticks(rotation = '25')  

use

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

Here's a minimal working example that illustrates your question and fix.

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()

This will result in the following figure:

question

, , - , , .
, plt.xticks ( ), :

answer

, y- (- np.random, . , x- , x.

, numpy 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 max x 2. max, , ( ).
  • [names[x.index(xi)] for xi in x_tick_location] , x_tick_location, x names.
  • , , xticks.
+3

All Articles