0

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.

Coconut
  • 29
  • 10
  • what do you mean by labelled data plots? As for why the code didn't work, try `plt.plot('x', 'y', data=dic)` – warped Nov 21 '20 at 22:20
  • Does [this](https://stackoverflow.com/questions/16010869/plot-a-bar-using-matplotlib-using-a-dictionary) answer your question? – Alpharoah Nov 21 '20 at 22:21
  • @warped Ohhh, thank you. I didn't know that the first two argument inputs for plt.plot should match the key values of the dictionary. Thanks very much. – Coconut Nov 21 '20 at 22:22
  • @Alpharoahi I looked at this post before making mine but it didn't help me. It's fine now as warped has pointed to my mistake. – Coconut Nov 21 '20 at 22:23
  • Just to create the connection to the docs: you need indexable objects, and you need to pass the respective indices to the function, along with the object. – warped Nov 21 '20 at 22:26
  • @warped Thank you. My error was thinking that the key names should have been defaulted as 'x' and 'y'. – Coconut Nov 21 '20 at 22:30

1 Answers1

1

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.

Coconut
  • 29
  • 10