0

Suppose I have two dictionaries in Python which might have different lengths and whose not all keys of one are in the other.

For example consider that the first dictionary has keys k1 and measurements m1 and the second k2 and m2. For example:

#1st dictionary
k = ['2015_05_06', '2015_05_26', '2016_03_03']
m1 = [10, 8.5, 19]
#second dictionary
k2 = ['2014_05_06', '2015_05_06', '2016_03_03']
m2 = [10, 13, 9]

If I do:

import matplotlib.pyplot as plt
plt.plot(k1, m1)
plt.plot(k2,m2)
plt.show()

The result is the followingenter image description here

Basically the x-axis which represents dates is not ordered and thus the second plot is plotting in the wrong x-axis position.

To solve this situation I thought to create a set of unique values such as:

 k = list(set(k1+k2))

but then the k and m1 and m2 have not the same length.

Is there a smart way to plot dictionaries with different keys in the same plot so that the keys on the x-axis are correctly ordered ?

1 Answer 1

1

One option is to turn your dates into a datetime object.

from datetime import datetime

d1 = [datetime.strptime(x, '%Y_%m_%d') for x in k]
d2 = [datetime.strptime(x, '%Y_%m_%d') for x in k2]

plt.plot(d1, m1, d2, m2)

Since the datetime objects maintain a complete order, your plot will be ordered too, but it will also reflect the different durations between each time step. enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Being inside a loop, can I do 2 separates plot? like plt.plot(d2, m2), plt.plot(d2, m2) and then plt.show()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.