Public id: Python Data Science

Akik Tongo takes off

As you all know, Matplotlib is a powerful Python visualization library that allows you to draw all kinds of diagrams. Matplotlib cheatsheet: Matplotlib cheatsheet: Matplotlib cheatsheet: Matplotlib cheatsheet

But! Today we do not take the ordinary road, just pick a few thieves to share the operation.

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) :
    print(xmin, xmax)
    return xmin, xmax
fig, ax = plt.subplots()
ax.plot([1.2.3.4.5.6.7], [10.50.100.23.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.5), (20.7)] 
yrange = (2.1) 
#Plotting the broken bar chart 
plt.broken_barh(xranges, yrange, 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

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', label='average per column') 
plt.xticks([]) 
plt.table(cellText=[['% 1.2 f' % xxx for xxx in xx] for xx in x],cellColours=plt.cm.GnBu(x),loc='bottom') 
plt.show()
Copy the code

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

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.show()
Copy the code

Article Reference:

Towardsdatascience.com/advanced-pl…

Share these first, and if you find them helpful, please share more and give them a like.

Welcome to follow my original wechat official account Python Data Science, focusing on writing data algorithms, machine learning, deep learning core dry products based on Python.