Pyplot - How do I plot multiple lines on the same graph when list lengths for one axis are not consistent?

Viewed 3196

I am trying to plot multiple lines on the same graph, one of the axis lists consists of dates and the other is a list of the numbers corresponding to each of the dates. However, when I go to plot the second line, the dates list is different in contents and length from first line plotted. So to try and fix this I put all of the dates used into 1 array and used this for the y-axis. This then left me with the issue of the x-axis never being the same length of as the y-axis causing an error. In an attempt to fix this I tried the following:

while len(y) != len(dates): 
    y.insert(0, 0)
plt.plot(dates, y)  # plots the line for x (dates) and y

This fixes the error however the graph now plots 0's when it should be plotting 1's.

image of Graph here

The graph should be plotting on 0.1 instead of 0.0

So what I'm asking is how would I fill the y-axis list with the zero's in the correct position, relevant to the dates, rather than putting all of the zero's at the beginning of the list?

1 Answers

Plot the two sets of data in separate calls. Here's an example:

from datetime import datetime

import matplotlib.pyplot as plt

derby_dates = [datetime(2020, 3, 1),
               datetime(2020, 3, 2),
               datetime(2020, 3, 3),
               datetime(2020, 3, 6)]
derby_cases = [1, 10, 7, 12]
nottingham_dates = [datetime(2020, 3, 1), datetime(2020, 3, 2)]
nottingham_cases = [2, 5]

plt.plot(derby_dates, derby_cases)
plt.plot(nottingham_dates, nottingham_cases)
plt.xticks(rotation=30)
plt.tight_layout()

plt.show()

That plots like this:

Plot image

Related