Einstein.py
Einstein.py

Reputation: 61

How do I plot a list all at once with matplotlib.pyplot?

I created a program that works out primes. It was just a test but I thought it would be interesting to then plot this on a graph.

import matplotlib.pyplot as plt

max = int(input("What is your max no?: "))
primeList = []

for x in range(2, max + 1):
  isPrime = True
  for y in range (2 , int(x ** 0.5) + 1):
     if x % y == 0:
        isPrime = False
        break

     if isPrime:
        primeList.append(x)


print(primeList)

How can I then plot primeList, can I do it all at once outside of the for loop?

Upvotes: 0

Views: 1115

Answers (1)

Mike Müller
Mike Müller

Reputation: 85442

This plots your list vs. its index:

from matplotlib import pyplot as plt

plt.plot(primeList, 'o')
plt.show()

This program:

from matplotlib import pyplot as plt

max_= 100
primeList = []

for x in range(2, max_ + 1):
    isPrime = True
    for y in range (2, int(x ** 0.5) + 1):
        if x % y == 0:
            isPrime = False
            break
    if isPrime:
        primeList.append(x)

plt.plot(primeList, 'o')
plt.show()

yields this plot:

enter image description here

Upvotes: 1

Related Questions