-3

I need some help with my Matplotlib graph. The project can be viewed here (currently working under the new-graph branch).

As a summary of what this project does:

  • Download two CSV files (UK COVID-19 cases and UK COVID-19 deaths)
  • Parse the CSV files as a Pandas data-frame to only have the columns with the date and the cumulative values
  • Plot these two sets of data on one graph using Matplotlib bar graph

My issue is that Matplotlib is not automatically spacing out the X-axis values (the dates). I'm not sure if it's because Matplotlib does not recognise them as dates or some other error I've made. Here is what the graph currently looks like.

EDIT: Sorry I forgot to add the code to the question. Here it is...

import matplotlib.pyplot as plt

def plot(cases,deaths):
    #cases.plot(x='Specimen date',y='Cumulative lab-confirmed cases',color='green')
    #deaths.plot(x='Reporting date',y='Cumulative deaths',color='red')
    plt.figure("Cumulative deaths and cases")
    ax = plt.gca()
    cases.plot(kind='bar', x='Specimen date', y='Cumulative lab-confirmed cases',ax=ax, color='green')
    deaths.plot(kind='bar', x='Reporting date', y='Cumulative deaths', ax=ax, color='red')
    plt.show()

2 Answers2

0

The problem is that you have far too many tick labels for the size of the plot.

I recommend spacing the ticks, such that it fits in your plot. This can be done with set_xticks, from Axis.axis. For instance, in the example below I am including a tick every 5 occurrences.

For improving readability further, I also included a rotation of 45 degrees on the tick labels. Note the parameter ha="right" there. It is used to make sure the right part of the label is the one aligned with the tick.

def plot(cases, deaths):
    plt.figure("Cumulative deaths and cases")
    ax = plt.gca()
    cases.plot(kind='bar', x='Specimen date', y='Cumulative lab-confirmed cases', ax=ax, color='green')
    deaths.plot(kind='bar', x='Reporting date', y='Cumulative deaths', ax=ax, color='red')
   
    ax.xaxis.set_ticks(range(0, len(cases), 5))
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")

    plt.show()
jpnadas
  • 774
  • 6
  • 17
-1

You probably want to make the xticks smaller using this function: plt.xticks(fontsize=desired_size)

Bram Dekker
  • 631
  • 1
  • 7
  • 19
  • Hi there, thanks for the reply. That seems to be a good workaround if I increase the size of the window. Is there a way I could space them out? E.g. 21/03/2020 ... 23/03/2020 ... (instead of them all being along the axis?) – SpiritedByte Jun 24 '20 at 12:56
  • @SpiritedByte You can use the parameter `rotation` in the `plt.xticks()` function to make the ticks horizontal if that is what you want. If you want the ticks to be on multiple lines, maybe this post is useful [link](https://stackoverflow.com/questions/20532614/multiple-lines-of-x-tick-labels-in-matplotlib). – Bram Dekker Jun 24 '20 at 13:21