As you all know, Matplotlib is a powerful Python visualization library that allows you to draw all kinds of diagrams. Some common uses were recently shared with Matplotlib’s official Cheatsheet. But! Today we do not take the ordinary road, just pick a few thieves to share the operation. Python Learning Exchange group, you can get PDF books, tutorials, etc for free.

1. Span Selector

Span Selector is a mouse widget in Matplotlib, and widgets are Python objects that contain some interactive functionality. Span Selector can be selected with the mouse box, making it easy to see the maximum and minimum values for the selected region.

Here’s the code. Start by creating a basic line chart as an example. We then call the SpanSelector method and use it to select a range, and display the maximum and minimum values in that range.

import matplotlib.pyplot as plt from matplotlib.widgets import SpanSelector def onselect(xmin, xmax): Plot ([1,2,3,4,5,6,7], print(xmin, xmax) return xmin, xmax (ax = plt.subplots() ax.plot([1,2,3,4,5,6,7], 24,15,28,45]) span = SpanSelector(ax, onSelect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show()Copy the code

The following is the specific operation.

2. Broken Barh

Broken’s horizontal bar graph is a discontinuous graph with gaps that can be used when data values vary widely, for example, data sets containing extreme temperature ranges. In this case, Broken’s horizontal bar charts are great because they can plot both the maximum and minimum range.

The Python module matplotlib.broken_barh() is used to draw horizontal bar charts for Broken.

Import matplotlib.pyplot as PLT #Defining the x and y ranges xranges = [(5,5), (20, 6),(20,7)] n = (2,1) #Plotting the node. Facecolors ='green') xranges = [(6,2), (17,5),(50,2)] yrange = (15,1) plt.broken_barh(xranges, yrange, Facecolors ='orange') xranges = [(5,2), (28,5),(40,2)] yrange = (30,1) plt.broken_barh(xranges, yrange, facecolors='red') plt.xlabel('Sales') plt.ylabel('Days of the Month') plt.show()Copy the code

! [](https://pic3.zhimg.com/80/v2-196ee4f65171e975fa9bd596285d253a_720w.jpg)

3. Table Demo

Matplotlib’s tables feature also allows you to display tables in diagrams. This is especially handy when we want to quickly view the values in a table as a bar chart. Tables can be placed at the top, bottom, or side of a chart.

import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.random.rand(5, 8)*.7 plt.plot(x.mean(axis=0), '-o', Plt.xticks ([]) plT.table (cellText=[['%1.2f' % XXX for XXX in xx] for XX in x],cellColours=plt.cm.GnBu(x),loc='bottom') plt.show()Copy the code

! [](https://pic1.zhimg.com/80/v2-cec3bfc39131562e81d31e5a9996cc7c_720w.jpg)
! [](https://pic2.zhimg.com/80/v2-6e585cc63936ab23f7335a338ac1c3e1_720w.jpg)

4. Watermark Images

Sometimes we feel that the background of the visualization is too monotonous and want to add a little bit of fun, such as overlaying the visualizations with data-related images as watermarks. Let’s take Lebron James of the NBA as an example to test the waters, and finally present lebron James’ statistics, with Lebron James himself in the background.

First, import the data set to be used, images, and the necessary library pandas.

import numpy as np 
import matplotlib.image as image 
import matplotlib.pyplot as plt 
import pandas as pd 
df = pd.read_csv('income.csv') 
im = image.imread('Lebron_James.jpeg') # Image
Copy the code

Use pandas to filter out data composed only of lebrons.

lebron_james = df[df['Name']=='LeBron James']
Copy the code

Then use figImage to add the watermark as follows.

fig, ax = plt.subplots() 
ax.grid() 
ax.plot('Year','earnings ($ million)',data=lebron_james) 
ax.set_title("LeBron James earnings in US$(millions)") 
fig.figimage(im, 60, 40,cmap='ocean', alpha=.2) 
plt.show()
Copy the code

! [](https://pic4.zhimg.com/80/v2-c4dbebc57ff910d2f4deb07da532a237_720w.jpg)

5. XKCD Plots

This one is even more interesting.

If you want to add some distortion to the Matplotlib graph, simply XKCD () calls methods on the Pyplot object, as shown below.

import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('https://raw.githubusercontent.com/parulnith/Website-articles-datasets/master/India%20GDP%20Growth%20Rate%20 .csv', parse_dates=['Year']) df['Year'] = df['Year'].apply(lambda x: pd.Timestamp(x).strftime('%Y')) #calling xkcd() method plt.xkcd(scale=5, length=400) df.plot(x='Year',y='GDP Growth (%)',kind='bar') plt.ylabel('GDP Growth (%)') plt.xticks(rotation=-20) PLT. Figure (figsize = (10, 8)) PLT. The show ()Copy the code

! [](https://pic2.zhimg.com/80/v2-cefa04a547fa3b77b67726891db398a9_720w.jpg)