Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set date tick labels on x axis, only for given points on matplotlib

I am trying to set date tick labels on x axis, only for given points. For example if I have a list of datetime for values on x axis

x = [ datetime.datetime(..), ... , datetime.datetime()]

I tried with ax.xaxis.set_ticklabels(x).

I want to plot date only for each one of six points present in list but I get this result:

plot

The code I used to get this plot is the following:

# figure's size in inch
fig = Figure(figsize=(8, 8))
# axes' position                                
ax = Axes(fig, [.1, .1, .8, .8])
ax.errorbar(matplotlib.dates.date2num(x), y, yerr=el['e'], fmt=format_string, label=label)

# shrinks current axis to 90%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])
# puts a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# autoscales axes following data limits
ax.autoscale(tight=False)

dateFmt = matplotlib.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(dateFmt)
monthsLoc = matplotlib.dates.MonthLocator()
daysLoc = matplotlib.dates.DayLocator(interval=1)
ax.xaxis.set_major_locator(monthsLoc)
ax.xaxis.set_minor_locator(daysLoc)
fig.autofmt_xdate(bottom=0.18)

# I tried to set tick labels with this but with no results
#ax.xaxis.set_ticklabels(x)
# adds axes to figure
fig.add_axes(ax)
# creates a canvas from figure
canvas = FigureCanvasAgg(fig)
# saves figure to filesystem in png format
canvas.print_figure(settings.MEDIA_ROOT + file_relative_path)

What am I doing wrong?

Thanks

like image 799
gc5 Avatar asked Oct 12 '12 11:10

gc5


People also ask

How do I label a specific point in Matplotlib?

To label the scatter plot points in Matplotlib, we can use the matplotlib. pyplot. annotate() function, which adds a string at the specified position.

How do you change X ticks in Matplotlib?

To change the default x ticks, use set_xticks() function in Matplotlib.

What are the Matplotlib methods we can use to adjust your X-axis tick marks?

Method 1 : xticks() and yticks() We can also set labels of the ticks of the axes using these functions, but, here we will focus only on changing the interval of ticks of axes. To know more about these functions click on xticks() and yticks().


1 Answers

To set ticks and their labels use:

x = [ datetime.datetime(..), ... , datetime.datetime()]
ax.xaxis.set_ticks(x)
like image 192
tillsten Avatar answered Oct 26 '22 22:10

tillsten