J. Williams
J. Williams

Reputation: 135

Plotting two dictionaries with Python

I have a problem going on. I tried to plot two dictionaries (with the same (number of) keys, but different values) in one graph. The idea is to make a line graph containing two lines; both dictionaries. The x-axis will be the dictionary keys, where the y-axis will be the values in both dicts. I managed to plot using

plt.plot(range(len(dict1)), dict1.values()) plt.plot(range(len(dict2)), dict2.values())

When i run the plot, it shows indeed two lines. But the x axis ticks (the keys from the dict (one or the other) are not sorted, while they were when I printed the dictionaries. I know this is due to the fact that getting the dict.values() creates an unsorted list. But when I change the plot data to this instead: plt.plot(range(len(dict1)), sorted(dict1.values())), the values shown in the plot won't change with it. The xticks are finally ordered, but the line graph does not match the right value anymore. How can I bypass this?

Upvotes: 0

Views: 6612

Answers (1)

Jerfov2
Jerfov2

Reputation: 5504

Dictionaries are unordered, so when you call keys or values and even sort them, they won't necessarily be in any order. However, when you call keys and values together and if the dictionary is not being modified, the lists returned by both these functions will contain the 'key:value' pairs in the same indexes. If keys in the dictionaries are numbers, then you can do this:

plt.plot(list(dict1.keys()), list(dict1.values()))

This converts the keys and values to lists, so you can use them as x and y values.

Upvotes: 1

Related Questions