Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating x axis tick labels in matplotlib

I have noticed that when I have 5 or less bars of data in my bar graph the x-axis automatically adds in extra ticks: enter image description here What I want is something like this:

enter image description here

Is there any way I can force matplotlib to generate just one tick label per bar for the first graph?

like image 710
Osmond Bishop Avatar asked Apr 03 '13 02:04

Osmond Bishop


People also ask

How do you change the x-axis label in MatPlotLib?

MatPlotLib with Python Using subplot() method, add a subplot to the current figure. Plot x and log(x) using plot() method. Set the label on X-axis using set_label() method, with fontsize=16, loc=left, and color=red. To set the xlabel at the end of X-axis, use the coordinates, x and y.

How do I change the format of a tick in MatPlotLib?

Tick formatters can be set in one of two ways, either by passing a str or function to set_major_formatter or set_minor_formatter , or by creating an instance of one of the various Formatter classes and providing that to set_major_formatter or set_minor_formatter .


1 Answers

The bar method takes a parameter align. Set this parameter as align='center'. align aligns the bars on the center of the x values we give it, instead of aligning on the left side of the bar (which is the default).

Then use the xticks method to specify how many ticks on the x-axis and where to place them.

import matplotlib.pyplot as plot

x = range(1, 7)
y = (0, 300, 300, 290, 320, 315)
plot.bar(x, y, width=0.7, align="center")

ind = range(2, 7)    # the x locations for the groups
plot.xticks(ind, x)

plot.axhline(305, linewidth=3, color='r')

plot.show()

Docs are at http://matplotlib.org/api/pyplot_api.html

like image 175
twasbrillig Avatar answered Oct 17 '22 03:10

twasbrillig