0

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?

4
  • Currently you're not plotting anything? Also, what would you plot against on your x-axis? You just need to supply x/y pairs in lists of equal length. Commented Feb 12, 2017 at 21:01
  • plt.plot(range(len(primeList)), primeList) for example. Commented Feb 12, 2017 at 21:05
  • I had an extra block of code that plotted that and a variable called itemsInList which was the amount of items in primeList Commented Feb 12, 2017 at 21:06
  • thanks @roganjosh that worked Commented Feb 12, 2017 at 21:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.