Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 472
Coder 477 Avatar asked Sep 20 '26 18:09

Coder 477


2 Answers

A sparkline is the same as a line plot but without axes or coordinates. They can be used to show the "shape" of the data in a compact way.

You can cram several line plots in the same figure just by using subplots and changing properties of the resulting Axes for each subplot:

data = np.cumsum(np.random.rand(1000)-0.5)
data = data - np.mean(data)

fig = plt.figure()
ax1 = fig.add_subplot(411) # nrows, ncols, plot_number, top sparkline
ax1.plot(data, 'b-')
ax1.axhline(c='grey', alpha=0.5)

ax2 = fig.add_subplot(412, sharex=ax1) 
ax2.plot(data, 'g-')
ax2.axhline(c='grey', alpha=0.5)

ax3 = fig.add_subplot(413, sharex=ax1)
ax3.plot(data, 'y-')
ax3.axhline(c='grey', alpha=0.5)

ax4 = fig.add_subplot(414, sharex=ax1) # bottom sparkline
ax4.plot(data, 'r-')
ax4.axhline(c='grey', alpha=0.5)


for axes in [ax1, ax2, ax3, ax4]: # remove all borders
    plt.setp(axes.get_xticklabels(), visible=False)
    plt.setp(axes.get_yticklabels(), visible=False)
    plt.setp(axes.get_xticklines(), visible=False)
    plt.setp(axes.get_yticklines(), visible=False)
    plt.setp(axes.spines.values(), visible=False)


# bottom sparkline
plt.setp(ax4.get_xticklabels(), visible=True)
plt.setp(ax4.get_xticklines(), visible=True)
ax4.xaxis.tick_bottom() # but onlyt the lower x ticks not x ticks at the top

plt.tight_layout()
plt.show()

sparklines

like image 81
RubenLaguna Avatar answered Sep 23 '26 07:09

RubenLaguna


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()
like image 21
hitzg Avatar answered Sep 23 '26 08:09

hitzg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!