Home > Back-end >  function for generating graph bar from a list
function for generating graph bar from a list

Time:11-11

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?

import matplotlib.pyplot as plt
import numpy as np
import math
%matplotlib inline

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}
                ]

# 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')

CodePudding user response:

Use list comprehension to get the "name" and "weight" from your list of dictionaries as follows:

def show_ducks_weights(duck_list):
    x = [d["name"] for d in duck_list]
    y = [d["weight"] for d in duck_list]
    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()

Note: I removed the filename argument because you don't seem to be using it.

  • Related