Search code examples
pythonpython-3.xwolfram-mathematicaprimes

How to plot a function showing discrete steps rather than continuous changes between samples in python?


I want to plot prime counting function as a step function using Python. I have done this using mathematica, picture below -

I want step wise graph like this one.

My python code

import numpy as np 
import matplotlib.pyplot as plt 
import sympy                        # for evaluating number of primes <= n 

def f(n):
    arr = []
    for i in range(1,n+1):
        arr.append(sympy.primepi(i))
        #print('For',i, 'value', arr[i-1])
    return arr

ar = f(100)

t1 = np.arange(1,101,1,dtype = int)
plt.plot(t1, ar ,'bo')           # instead of 'bo' what I need to use to make it like 1st picture?
plt.axis([0,110,0,25]) 
plt.show()

which produces

this image.

Can anyone tell me how to make this graph stepwise as it is in the first image? and please share if there is any other good way to do this task which will be efficient.

References:

  1. For more on prime counting function see here.

Solution

  • Matplotlib has a step function implemented.

    Just replace plot by step:

    plt.step(t1, ar)
    

    Note that you can control where the steps are rising via the kwarg where and it's values {'pre', 'post', 'mid'}