0

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?

2
  • 1
    You need to sort the values by the key, not the value. Commented Mar 22, 2017 at 17:56
  • 1
    I plot two dicts in the morning, I plot two dict's at night [...] and at every 10,000 points, I plot two dicts. Commented Mar 22, 2017 at 17:57

1 Answer 1

1

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.

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

7 Comments

They are floats, containing a date type
It does not work, because the keys in my dictionaries are floats. If not, it would indeed work: "ValueError: invalid literal for float()"
You asked The x-axis will be the dictionary keys, where the y-axis will be the values. Is this isn't want you want, what do you want?
That is right, but it won't work this way, because the dict keys are not the correct type. Setting the x-axis separately as xticks only works at the moment.
@J.Williams check my new answer. Add list around the keys and values
|

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.