Some days ago I was asked which graph library I usually use…well, none daily.
I’ve colleagues using
- D3.js or
- matplotlib
Since I’m neither a JavaScript guru nor a Python expert it was the cool XKCD style that hooked me to matplotlib: Pimp your Charts with the fancy XKCD Style.
Usually, I’m fine with the raw data/numbers in my daily work. Let’s pick a basic example: X-ray a Git repository.
When did I publish my last post Wrap Java Libraries as OSGi Bundles with Maven?
$ git log -1 --format=%cd --relative-date content/Wrap\ Java\ Libraries\ as\ OSGi\ Bundles\ with\ Maven.md
7 weeks ago
What’s the inception date of the Git powered version of {devops blog}?
$ git log $(git rev-list --max-parents=0 HEAD) --format=%cd --relative-date
4 years, 11 months ago
When did the last change hit the repo?
$ git log -1 --format=%cd --relative-date
3 weeks ago
Let’s double-check the saying: a picture is worth a 1000 words and get through the nice XKCD showcase step by step:
Step 1 - Hello XKCD World
Prepare the empty basic figure with two axes only.
with plt.xkcd():
fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_xticks([])
ax.set_yticks([])
For more details about tuing the axes check matplotlib.axes.
Step 2 - The Timeline
Add two ticks to the x-axis to get a grip on the Blog Events we want to visualize.
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks([0, 240])
ax.set_xticklabels(['4 years, 11 months ago', '7 weeks ago'])
ax.set_xlim([-25, 260])
The time we cover is roughly 250 weeks, so we set xlim
to a range of [-25, 260]
to put our data in between.
Step 3 - Scatter the Data
We put the data in a human readable array and feed it via numpy.ndarray.T in the required format to the matplotlib.pyplot.scatter function like follows:
data = np.array([
[0, 1],
[240, 1],
[250, 1],
])
x, y = data.T
plt.scatter(x,y)
Step 4 - Finishing Touches
With matplotlib.pyplot.text we are trying to make the figure a bit more self-explanatory…
plt.text(0, 1, 'migration from\nPebble to Pelican', withdash=True,
dashdirection=1,
dashpad=10,
dashlength=25,
dashpush=10,
dashrotation=45)
Seems like time for another post 🤔- maybe about my First Steps with Matplotlib...?
Header cover Photo by Samuel Zeller