#๐Ÿ”’ Using matplotlib to graph the efficiency of sorting algorithms.

78 messages ยท Page 1 of 1 (latest)

graceful sable
#

i need some help using matplotlib

north geyserBOT
#

@graceful sable

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

graceful sable
#
def graph_efficiency():
    plt.plot([], [])
    plt.xticks([0, 1000, 5000, 10000, 100000, 500000, 1000000])
    plt.axis((0, 60, 0, 1000000))
    plt.ylabel('Time Taken')
    plt.show()
    #plt.savefig("plot.png")
vocal shoal
#

The plt.axis line is the one giving you trouble

#

Also you are making an empty plot

graceful sable
#

yeah i havent got anything to plot yet

#

well i do

#

but idk how to represent it yet

vocal shoal
#

So what could some sample data look like? That would make it easier

graceful sable
#

well right now i have this

#
Bubble: Sorted list in 5.3916 seconds
Insertion: Sorted list in 0.9112 seconds
#

so i have the time it takes each algo takes to sort 10000 items

vocal shoal
#

You probably want a bar graph for showing different run times instead of a scatter plot / line plot

eager wharf
#

they want to plot N vs time taken for N

vocal shoal
#

Ah

graceful sable
#

yeah i want the time it takes for each algo to sort lists from 1000 size to 1,000,000

#

and then graph it

vocal shoal
#

Then yeah multiple line plots would be good

graceful sable
#

to compare the efficiency

vocal shoal
#

Do you already have those times for each algorithm?

graceful sable
#

only for 10,000

#

but shouldnt be difficult to get the rest

#

its all split into funcs

eager wharf
#

first get the times you want into a list

graceful sable
#

can i get my axis ready first?

vocal shoal
#
______| 1000 | 10,000 | 100,000 | 1,000,000
------|------|--------|---------|----------
Bubble|   1  |   3    |    5    |    100
------|------|--------|---------|----------
Insert|  0.5 |  2.5   | 7.5     |   50

If you already have some data like this it can be straightforward to plot

graceful sable
#

2d list?

vocal shoal
#

I would have your data use the same x-values, set the x-axis ticks and labels to those values, then calculate your max run time and adjust the y-axis to the value

graceful sable
#

yeah i was going to

scenic silo
graceful sable
#
sort_list_1000 = generate_unsorted_list(1000)
sort_list_5000 = generate_unsorted_list(5000)
sort_list_10000 = generate_unsorted_list(10000)
sort_list_100000 = generate_unsorted_list(100000)
sort_list_500000 = generate_unsorted_list(500000)
sort_list_1000000 = generate_unsorted_list(1000000)
#

thats what i have

vocal shoal
#

That looks like what would be the input data to your different algos

#

But once you have that runtime data, I would imagine it looks like this:

bubble_data = [1, 3, 5, 100]
insert_data = [0.5, 2.5, 7.5, 50]
graceful sable
#

im just getting it setup

#

this is really innefficient lol

#
sort_list_1000 = generate_unsorted_list(1000)
    sort_list_5000 = generate_unsorted_list(5000)
    sort_list_10000 = generate_unsorted_list(10000)
    sort_list_100000 = generate_unsorted_list(100000)
    sort_list_500000 = generate_unsorted_list(500000)
    sort_list_1000000 = generate_unsorted_list(1000000)
    bubble_sort_result_1000, bubble_elapsed_1000 = time_sort(bubble_sort, sort_list_1000)
    bubble_sort_result_5000, bubble_elapsed_5000 = time_sort(bubble_sort, sort_list_5000)
    bubble_sort_result_10000, bubble_elapsed_10000 = time_sort(bubble_sort, sort_list_10000)
    bubble_sort_result_100000, bubble_elapsed_100000 = time_sort(bubble_sort, sort_list_100000)
    bubble_sort_result_500000, bubble_elapsed_500000 = time_sort(bubble_sort, sort_list_500000)
    bubble_sort_result_1000000, bubble_elapsed_1000000 = time_sort(bubble_sort, sort_list_1000000)

    insertion_sort_result_1000, insertion_elapsed_1000 = time_sort(insertion_sort, sort_list_1000)
    insertion_sort_result_5000, insertion_elapsed_5000 = time_sort(insertion_sort, sort_list_5000)
    insertion_sort_result_10000, insertion_elapsed_10000 = time_sort(insertion_sort, sort_list_10000)
    insertion_sort_result_100000, insertion_elapsed_100000 = time_sort(insertion_sort, sort_list_100000)
    insertion_sort_result_500000, insertion_elapsed_500000 = time_sort(insertion_sort, sort_list_500000)
    insertion_sort_result_1000000, insertion_elapsed_1000000 = time_sort(insertion_sort, sort_list_1000000)
vocal shoal
#

Then you could plot it (and I would strongly recommend using a logarithmic scale for your x-axis)

bubble_data = [1, 3, 5, 100]
insert_data = [0.5, 2.5, 7.5, 50]

fig, ax = plt.subplots()

ax.plot([1000, 10000, 100000, 1000000], bubble_data)
ax.plot([1000, 10000, 100000, 1000000], insert_data)
ax.set_xticklabels([1000, 10000, 100000, 1000000])
ax.set_xscale("log")
plt.show()
graceful sable
#

this is taking a long time to sort 1,000,000 elements

#

i dont even know if my program is running

vocal shoal
#

Surely you know the concept of logarithms right?

graceful sable
#

im not sure

#

also i think 1,000,000 elements might be too muhc

vocal shoal
#

What do you think of the graph above?

#

See how the x-axis scales by powers of 10?

#

If it is linear, it looks silly

graceful sable
#

oh yeah i see

vocal shoal
graceful sable
#

yeah my program isnt respondinng

#

been waiting for ages now

#

atleast i think its not working

vocal shoal
#

You are probably finding how data processing times scales at large numbers

#

Big O notation is a way to describe that behavior

graceful sable
#

i also havent learn that

#

we do that in data analytics

graceful sable
vocal shoal
#

Its just a way to describe how algorithms behave. Knowing that some scale better than others is good to know

graceful sable
#

damn it this ruins like my whole program

#

my computer is too shit to run the long sorting lists

eager wharf
#

you can still get a useful graph even if you limit it to like 10k or 100k

graceful sable
#

its stuggling with 100k i think

#
import time, random
import matplotlib.pyplot as plt
from collections.abc import Callable

def bubble_sort(mylist: list) -> list:
    for i in range(len(mylist)-1):
        for x in range(len(mylist)-(1+i)):
            if mylist[x] > mylist[x+1]:
                mylist[x], mylist[x+1] = mylist[x+1], mylist[x]
    return mylist

def insertion_sort(mylist: list) -> list:
    sortedlist = []
    for i in range(len(mylist)):
        insert_into_sorted(sortedlist, mylist[i])
    return sortedlist

def insert_into_sorted(mylist: list, element: int) -> None:
    for i in range(len(mylist)):
        if element < mylist[i]:
            mylist.insert(i, element)
            return
    mylist.append(element)

def generate_unsorted_list(size: int) -> list:
    unsorted_list = []
    for i in range(size):
        unsorted_list.append(random.randint(1, 1000000))
    return unsorted_list

def time_sort(sorting_method: Callable[[list], list], mylist: list) -> tuple[list, float]:
    copied_list = mylist.copy()
    start = time.time()
    sorted_list = sorting_method(copied_list) 
    end = time.time()
    elapsed_time = end - start
    return sorted_list, elapsed_time

def graph_efficiency():
    plt.plot([], [])
    plt.xticks([0, 1000, 5000, 10000, 100000, 500000, 1000000])
    plt.axis((0, 60, 0, 1000000))
    plt.ylabel('Time Taken')
    plt.show()
    #plt.savefig("plot.png")

def main():
    sort_list_100000 = generate_unsorted_list(100000)
    insertion_sort_result_100000, insertion_elapsed_100000 = time_sort(insertion_sort, sort_list_100000)
    print(f"Insertion: Sorted list in {insertion_elapsed_100000:.4f} seconds")

main()
#

does this look okay?

vocal shoal
#

Well you never call your plotting function, and you don't plot the individual results

graceful sable
#

i just wanna see the time for sortingh

vocal shoal
#

For the time being I would scale it down to like 10, 50, 100, 250, 500 items

graceful sable
#

okay

#

whats my best way to run my sorts on all those different amount of items

#

@vocal shoal ^^

vocal shoal
#

Probably sequentially and add the runtime to a list of some kind

vocal shoal
#

Generating the data for runtime at different scales is definitely the slow and hard part of this

Saving the data is the most important part so you don't have to run it again

Displaying the data in a meaningful way is the easiest part, but also the most visual and can lead to insights

north geyserBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.