Search code examples
pythonpygal

How to set spacing between dates on x-axis in a graph when using pygal for plot generation?


I am currently using pygal for graph generation and I am having issue with dates on x-axis as their number is increasing and they are starting to overlap. I want to either provide spacing among the dates or put the dates there weekly.

If anyone can help it would be quite appreciable. Thank you.


Solution

  • You can:

    1) set value for x_label_rotation parameter to rotate date clockwise.
    2) get every N date in x-axis, where N you can adjust. You should set show_minor_x_labels=False.

    For example:

    import random
    import pygal
    chart = pygal.Line(x_label_rotation=20)
    date_list = [datetime(2017, 1, 30, 0, 0, n) for n in range(0, 60)]
    values_list = [random.randint(5, 20) for n in range(0, 60)]
    chart.x_labels = date_list
    chart.add('line', values_list)
    chart.render_to_file('your_path_to_file') #f.e /Users/{user_name}/Documents/chart.svg
    

    After that we are getting overlapped dates:

    enter image description here

    Next, consider modified snippet of code:

    import random
    import pygal
    chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
    date_list = [datetime(2017, 1, 30, 0, 0, n) for n in range(0, 60)]
    values_list = [random.randint(5, 20) for n in range(0, 60)]
    chart.x_labels = date_list
    N = 5 # we will plot only every 5 date from date_list
    chart.x_labels_major = date_list[::N]
    chart.add('line', values_list)
    chart.render_to_file('your_path_to_file') #f.e /Users/{user_name}/Documents/chart.svg
    

    After that we aren't getting overlapped dates:

    enter image description here