There's more...

You may want to change the format in which the values are presented. In our example, maybe the numbers represent millions of dollars. To do so, you can add a formatter to the y axis, so the values represented there will have it applied to them:

>>> from matplotlib.ticker import FuncFormatter

>>> def value_format(value, position):
... return '$ {}M'.format(int(value))

>>> axes = plt.gca()
>>> axes.yaxis.set_major_formatter(FuncFormatter(value_format))

value_format is a function that returns a value based on the value and position of the data. Here, it will return the value 100 as $ 100 M.

Values will be retrieved as floats, requiring you to transform them into integers for display.

To apply the formatter, we need to retrieve the axis object with .gca (get current axes). Then, the .yaxis gets the formatter.

The color of the bars can also be determined with the color parameter. Colors can be specified in multiple formats, as described in https://matplotlib.org/api/colors_api.html, but my favorite is following the XKCD color survey, using the xkcd: prefix (no space after the colon):

>>> plt.bar(POS, VALUES, color='xkcd:moss green')

The full survey can be found here: https://xkcd.com/color/rgb/.

Most common colors, such as blue or red, are also available for quick tests. They tend to be a little bright to be used in good-looking reports, though.

Combining the color with formatting the axis gives the following result:

Bar graphs don't need to display information in a temporal way. As we've seen, matplotlib requires us to specify the X parameter of each bar. That's a powerful tool to generate all kinds of graphs.

For example, the bars can be arranged to display a histogram, such as for displaying people of a certain height. The bars will start at a low height, increase to the average size, and then drop back. Don't limit yourself to just spreadsheet charts!

The full matplotlib documentation can be found here: https://matplotlib.org/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.156.55