Coconut
Coconut

Reputation: 29

How do you plot labelled data by using a dictionary in Matplotlib? (Python)

According to Matplotlib's documentation, you can make a plot by using a dictionary to store the values for the x and y axes:

"There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array."

The language on this page is a bit technical, so I am not completely sure how to present the dictionary so I can get a working plot. I attempted to use this as an example, but it was unsuccessful:

from matplotlib import pyplot as plt

dic = {"x": [1, 2, 3, 4, 5], "y": [2, 4, 6, 8, 10] } 

plt.plot('xlabel', 'ylabel', data=dic)

May someone explain to me the way in which the structure of the dictionary should be presented to allow for labelled data plots please? Thank you.

Edit: For clarity, the values for the key "x" should be the x-values, and the values for the key "y" should be the y-values of the plot for my example.

2nd edit: This problem has been solved. I understand now that my problem was not matching the name of the first two argument inputs for plt.plot() to the key names in my dictionary.

Upvotes: 0

Views: 1729

Answers (1)

Coconut
Coconut

Reputation: 29

This problem has been solved. I understand now that my problem was not matching the name of the first two argument inputs for plt.plot() to the key names in my dictionary. E.g.

plt.plot('xlabel', 'ylabel', data=dic)

Should have been

plt.plot('x', 'y', data=dic)

Thanks to the user 'warped' who commented below my question, pointing out the mistake.

Upvotes: 1

Related Questions