Search code examples
pythonmatplotlibsparklines

Creating sparklines using matplotlib in python


I am working on matplotlib and created some graphs like bar chart, bubble chart and others.

Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ?

for example with the following code

import matplotlib.pyplot as plt
import numpy as np
x=[1,2,3,4,5]
y=[5,7,2,6,2]
plt.plot(x, y)
plt.show()

the line graph generated is the following:enter image description here

But I couldn't get what is the difference between a line chart and a spark lien chart for the same data. Please help me understand


Solution

  • A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # create some random data
    x = np.cumsum(np.random.rand(1000)-0.5)
    
    # plot it
    fig, ax = plt.subplots(1,1,figsize=(10,3))
    plt.plot(x, color='k')
    plt.plot(len(x)-1, x[-1], color='r', marker='o')
    
    # remove all the axes
    for k,v in ax.spines.items():
        v.set_visible(False)
    ax.set_xticks([])
    ax.set_yticks([])
    
    #show it
    plt.show()