Skip to content Skip to sidebar Skip to footer

Creating Bar Charts In Python

I have a couple of problems with the Bar Chart that I'm trying to create in python. My code for the chart looks like this: import matplotlib matplotlib.use('Agg') from pylab impor

Solution 1:

First up, I would use a figure object to work on: this makes it easier to construct the plot to your liking. To construct your graph, the following should do:

fig = plt.figure()
fig.subplots_adjust(bottom=0.2)          # Remark 1
ax = fig.add_subplot(111)
ax.bar(arange(len(grosses)), grosses)
ax.ticklabel_format(style='plain')       # Remark 2
ax.set_xticks(arange(len(genres)))
ax.set_xticklabels(genres, rotation=80)
savefig('barchart.png', dpi=500)

Along with the following remarks:

  1. This adjusts the size of your image, in this case it enlarges the bottom to be able to fit your labels. In most cases you roughly know the data you are going to put in, so that should suffice. If you are using matplotlib version 1.1 or higher, you could use the tight_layout function to do this automatically for you. The alternative is to calculate the needed size by yourself based on the bounding boxes of all axes labels as shown here, but you need a renderer for this to be able to determine the sizes of all labels.
  2. By specifying the label format (using either sci or plain), you can change the rendering of the values. When using plain, it will just render the value as is. See the docs on this function for more info. Note that you can also use the set_yticklabels function's text argument to control the formatting further (of course that function is also available for the x axis.

Post a Comment for "Creating Bar Charts In Python"