Nov-10-2021, 01:08 PM
I had to generate a bar chart from a list. I solved it in the simple way with no problems (Task 3a in the code below).
After that I wanted to write the code in the form of function (Task 3b).
The code 3b works well too, BUT now I'm struggling to understand if there is a way to avoid of writing again the full list of names ['Jerome','Ibraheem','Tiana','Lucas','Rickie'] and weights [3.38, 3.08, 0.81, 3.33, 4.4] for "x" and "y" inside the function and make it simpler.
Anybody can help with this?
After that I wanted to write the code in the form of function (Task 3b).
The code 3b works well too, BUT now I'm struggling to understand if there is a way to avoid of writing again the full list of names ['Jerome','Ibraheem','Tiana','Lucas','Rickie'] and weights [3.38, 3.08, 0.81, 3.33, 4.4] for "x" and "y" inside the function and make it simpler.
Anybody can help with this?
import matplotlib.pyplot as plt import numpy as np import math %matplotlib inline def main(duck_list_1,duck_list_2): return main duck_list_1 = [ {'name': 'Jerome', 'weight': 3.38, 'wingspan': 49.96, 'length': 19.75}, {'name': 'Ibraheem', 'weight': 3.08, 'wingspan': 50.59, 'length': 20.6}, {'name': 'Tiana', 'weight': 0.81, 'wingspan': 47.86, 'length': 17.94}, {'name': 'Lucas', 'weight': 3.33, 'wingspan': 48.27, 'length': 18.77}, {'name': 'Rickie', 'weight': 4.4, 'wingspan': 51.0, 'length': 20.34} ] duck_list_2 = [ {'name': 'Mysha', 'weight': 6.05, 'wingspan': 60.05, 'length': 30.52}, {'name': 'Ruben', 'weight': 3.99, 'wingspan': 60.36, 'length': 30.46}, {'name': 'Tara', 'weight': 6.99, 'wingspan': 62.0, 'length': 32.7}, {'name': 'Shaurya', 'weight': 6.63, 'wingspan': 61.7, 'length': 31.82} ] # Task 3a generate the graph bar (simple solution) fig1a, ax = plt.subplots(figsize=(12, 8), dpi=90) ax.bar(['Jerome','Ibraheem','Tiana','Lucas','Rickie'], [3.38, 3.08, 0.81, 3.33, 4.4], color='b') ax.set_title("Show Duck Values") ax.set_xlabel("Duck Name") ax.set_ylabel("Weight") plt.show() print() # Task 3b create a function to generate a graph bar (function solution) def show_ducks_weights(duck_list,filename): x = ['Jerome','Ibraheem','Tiana','Lucas','Rickie'] y = [3.38, 3.08, 0.81, 3.33, 4.4] fig1b, ax = plt.subplots(figsize=(12, 8), dpi=90) ax.bar(x,y, color='b') ax.set_title("Show Duck Values") ax.set_xlabel("Duck Name") ax.set_ylabel("Weight") plt.show() show_ducks_weights(duck_list_1, 'weight')