1

Unable to create a graph using Matplotlib whilst using this dictionary. Trying to be able to choose the two values, then produce a graph.

Eg. select USD and GBP and plot graph.

import matplotlib.pyplot as plt

exchange_rates = {
    "GBP": {
    "USD": 1.2,
    "EUR": 1.1
},
"USD": {
    "GBP": 1.18,
    "EUR": 1.07
},
"CZK": {
    "GBP": 28.7934,
    "EUR": 29.654,
    "USD": 40.345
    }
}
def make_a_graph():
    plt.bar(range(len(exchange_rates)), exchange_rates.values())
    plt.xticks(range(len(exchange_rates)), list(exchange_rates.keys()))
    plt.show()

1 Answers1

2

In your code, exchange_rates is a dictionnary which itself contains dictionnaries. You should do double dereferencing in order to plot the values.

def make_a_graph(exchange_rates):
    x=len(exchange_rates["CZK"])
    y1=exchange_rates["CZK"]  
    plt.bar(range(x),y1.values())
    plt.show()

Note you have to be consistent with the length of the quantities you want to plot. I have plotted only one key above.

lefloxy
  • 181
  • 7
  • Traceback (most recent call last): File "/Users/Andrew/Desktop/Python_Uni/1.3 #.py", line 106, in app() File "/Users/Andrew/Desktop/Python_Uni/1.3 #.py", line 95, in app make_a_graph() File "/Users/Andrew/Desktop/Python_Uni/1.3 #.py", line 77, in make_a_graph plt.bar(range(x), y1.values()) – Andrew Shakespeare Apr 24 '18 at 14:10
  • File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2770, in bar ret = ax.bar(*args, **kwargs) File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/matplotlib/__init__.py", line 1855, in inner return func(ax, *args, **kwargs) File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 2233, in bar np.atleast_1d(x), height, width, y, linewidth) – Andrew Shakespeare Apr 24 '18 at 14:11
  • File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 249, in broadcast_arrays shape = _broadcast_shape(*args) File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 184, in _broadcast_shape b = np.broadcast(*args[:32]) ValueError: shape mismatch: objects cannot be broadcast to a single shape – Andrew Shakespeare Apr 24 '18 at 14:11
  • This is the error after implementing that bit of code – Andrew Shakespeare Apr 24 '18 at 14:11
  • @AndrewShakespeare You should pass the dictionary as parameter to the function make_a_graph – lefloxy Apr 24 '18 at 14:13