Skip to content
Advertisement

How to prevent x-axis labels from overlapping

I’m generating a bar-chart with matplotlib. It all works well but I can’t figure out how to prevent the labels of the x-axis from overlapping each other. Here an example:
enter image description here

Here is some sample SQL for a postgres 9.1 database:

JavaScript

And this is my python-script:

JavaScript

Is there a way how I can prevent the labels from overlapping each other? Ideally in an automatic way, because I can’t predict the amount of bars.

Advertisement

Answer

  • The issue in the OP is the dates are formatted as string type. matplotlib plots every value as a tick label with the tick location being a 0 indexed number based on the number of values.
  • The resolution to this issue is to convert all values to the correct type, datetime in this case.
    • Once the axes have the correct type, there are additional matplotlib methods, which can be used to further customize the tick spacing.
  • The answers to What is plotted when string data is passed to the matplotlib API? explain in more detail what happens when string values are passed to matplotlib.
  • As of 2014-09-30, pandas has a read_sql function, which has a parse_dates parameter. You definitely want to use that instead.

Original Answer

Here’s how you should convert your date string into real datetime objects:

JavaScript

enter image description here

Getting a simple list of tuples out of your database cursor should be as simple as…

JavaScript

However, I posted a version of a function that I use to take db cursors directly to record arrays or pandas dataframes here: How to convert SQL Query result to PANDAS Data Structure?

Hopefully that helps too.

Advertisement