Matplotlib is a 2D drawing library for Python. Numerous academic journals, books and publications use it to create professional data visualizations. Matplotlib is cross-platform and runs in Python scripts, Python interpreters, IPython, Jupyter Notebook, Web application servers, and four GUI (Graphical User Interface) toolkits. With matplotlib, you can draw line charts, histograms, power Spectra, bar charts, error charts, scatter charts, etc., with just a few lines of code.
1. Install
pip install matplotlib
Copy the code
2. The import
In the jupyter Notebook environment, you need to add %matplotlib inline so that the drawing will be generated on the notebook page. Other environments need to remove %matplotlib inline.
import matplotlib.pyplot as plt
%matplotlib inline
Copy the code
3. Basic concepts
Matplotlib defines four basic concepts: Figure, axes, Axis, and artist. Understanding these four basic concepts will give you a better understanding and proficiency in using Matplotlib to draw the graphs you want.
To visualize these four concepts, there is no better way to draw these abstract concepts than directly using Matplotlib.
import numpy as np
figure, axes = plt.subplots(1.2, figsize=(8.4))
figure.suptitle("figure")
x = np.linspace(0.2.100)
axes1, axes2 = axes
axes1.plot(x, x, label='artist legend')
axes2.plot(x, x**2, label='artist legend')
axes1.set_title("axes 1")
axes2.set_title("axes 2")
axes1.set_xlabel("axis x of axes 1")
axes2.set_xlabel("axis x of axes 2")
axes1.set_ylabel("axis y of axes 1")
axes2.set_ylabel("axis y of axes 2")
axes1.legend()
axes2.legend()
axes1.grid()
axes2.grid()
plt.show()
Copy the code
By observing the drawn chart, we can intuitively see the specific representation of each “abstract concept” in the chart and the hierarchical relationship between them.
With these visualizations, it’s easy to understand them one by one.
Figure 3.1
As can be seen from the figure, figure represents the whole drawing area and more importantly acts as a container. All other drawing elements must be included in the figure. The figsize parameter is used to define the size of the figure and the size of the drawing area. In addition, it is possible to set a title for the entire drawing area using the figure.suptitle(title) method, but this is not required (in fact, figure’s existence as a container would not be intuitive without a title).
Thus, to draw a chart or any visual rendering using Matplotlib, you must first create a figure object either explicitly or implicitly (when drawn directly using functions such as plt.plot).
Here are two of the most common ways to create a figure. According to personal habits, you can choose one way. Individuals tend to use the second method.
Figure (num=None, figsize=None, dPI =None, facecolor=None, edgecolor=None, frameon=True, clear=False)
Plt.figure () is any underlying factory function that creates a figure object. It provides all the details for creating figures.
parameter | describe |
---|---|
num | An integer or a string. Figure number, namely the number attribute of figure object, can be understood as the ID of figure object; If the figure numbered num already exists in the context, the existing figure reference is returned without creating a new figure. Default to None, creates a new figure object and increments number by 1. |
figsize | Tuples. Figure width and height in feet. The default value ismatplotlib.rcParams["figure.figsize"] 。 |
dpi | An integer. Resolution. The default value ismatplotlib.rcParams["figure.dpi"] 。 |
facecolor | String or color object. Background color. The default is white. |
edgecolor | String or color object. Border color. The default is white. |
frameon | Bool. |
clear | Bool. When True, empty the drawing of the existing figure. The default value is not clear. |
Example code to understand the use of num:
figure1 = plt.figure()
print("this is a new figure instance, whose number is {}.\n".format(figure1.number))
figure2 = plt.figure()
print("this is a new figure instance, whose number is {}.\n".format(figure2.number))
figure1_ref = plt.figure(num=1) # Equivalent to PLt. figure(1)
print("this is a existed figure instance, whose number is {}.\n".format(figure1_ref.number))
if figure1_ref == figure1:
print("figure1_ref is equal to figure1.")
plt.show()
Copy the code
As you can see, when the script above runs, no visible chart is displayed. As mentioned above, figure is just a container, and what we really think of is axes contained in figure container with coordinate system. A figure created using the plt.figure() method must call a plotting function such as plt.plot() to display a chart. The code is as follows:
# figure 1
plt.figure(figsize=(9.3))
plt.suptitle("figure 1")
names = ['a'.'b'.'c']
values = [1.10.100]
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.show()
# figure 2
plt.figure(figsize=(9.3))
plt.suptitle("figure 2")
names = ['d'.'e'.'f']
values = [100.10.1]
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.show()
Copy the code
5.plots (nROWS =1, nCOLs =1, sharex=False, sharey=False, figsize=None)
Plt.subplots () is an extra wrapper on PLT.figure () and provides a convenient way to create figure and axes in one go. In fact, any parameters supported by PLt.figure (), such as the figsize parameter, will be passed by plt.figure(), except for nrows, nCOLs, sharex, sharey, etc.
Plt.subplots () returns a tuple. The first element of the tuple is the figure object; The second element is the AXES object used to draw the graph. Note that when nROWS, nCOLs creates more than one AXES, the second element of the tuple is the NUMpy array of one AXES object.
It can be seen that, unlike PLT.figure (), plt.subplots() also creates one or more axes objects when it creates the figure object. As a result, the diagram is visible once created.
The following code creates a figure object containing 2 rows, 3 columns and 6 axes.
figure, axes = plt.subplots(2.3, figsize=(9.6))
figure.suptitle("2 rows 3 cols")
plt.show()
print("type of return tuple[1] is {}".format(type(axes)))
Copy the code
If nRows and NCOLs are omitted, only one AXES will be created. As follows:
figure, axes = plt.subplots()
figure.suptitle("only one axes")
plt.show()
print("type of return tuple[1] is {}".format(type(axes)))
Copy the code
3.2 axes
“This is what you think of as ‘a plot'”.
After the above discussion, I believe that understand the above sentence, simply “So easy!” . That’s right, axes is the real hero of our fancy graphs!
As mentioned above, the chart created using the plt.subplots() method will return the contained AXES object. These axes objects are the object-oriented interfaces that Matplotlib provides to plot graphs. Using various axes object drawing methods, you can draw any chart, text, and picture on a chart corresponding to the AXES coordinate space.
3.2.1 the plot ([x], y, (FMT))
Draw a line graph or label with x as the horizontal axis and y as the vertical axis and FMT as the format string (defining colors, markers, linelines, etc.). And can define multiple X, Y, FMT combination, draw multiple different graphics at one time.
Some drawing examples are provided below.
Draw different figures in the same AXES:
figure, axes = plt.subplots()
t = np.arange(0..5..0.2)
axes.plot(t, t, 'r--', t, t**2.'bs', t, t**3.'g^')
plt.show()
Copy the code
Draw different axes in a figure and share the x axis:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0.5.0.0.1)
t2 = np.arange(0.0.5.0.0.02)
figure, axes = plt.subplots(2.1, sharex=True)
ax1, ax2 = axes
ax1.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
ax2.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
Copy the code
Scatter (x, y, S =None, C =None, alpha=None)
X axis; Y vertical axis; Size of point s, default is rcParams[‘lines.markersize’] square; C color; Alpha transparency.
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
Copy the code
Bar (x, height, width=0.8)
X-coordinate position; Height bar height; Width Width of the bar.
plt.rcParams['font.sans-serif'] = ['SimHei'] # used to display Chinese labels normally
plt.rcParams['axes.unicode_minus'] = False # is used to display the minus sign normally
labels = ['G1'.'G2'.'G3'.'G4'.'G5']
men_means = [20.34.30.35.27]
women_means = [25.32.34.20.25]
x = np.arange(len(labels)) # tag position
width = 0.35 # Bar width
fig, ax = plt.subplots()
# Draw a bar chart
rects1 = ax.bar(x - width/2, men_means, width, label='male')
rects2 = ax.bar(x + width/2, women_means, width, label='woman')
ax.set_ylabel('score')
ax.set_title('Gender score by group')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
""" Adds text to each bar to show the height of the bar """
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0.3), Add three points of vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
Copy the code
3.2.4 Horizontal bar chart: Barh (y, width, height=0.8)
Y-coordinate position; Width Bar width; Height Bar height.
category_names = ['Strongly disagree'.'Disagree'.'Neither agree nor disagree'.'Agree'.'Strongly agree']
results = {
'Question 1': [10.15.17.32.26].'Question 2': [26.22.29.10.13].'Question 3': [35.37.7.2.19].'Question 4': [32.11.9.15.33].'Question 5': [21.29.5.5.40].'Question 6': [8.19.5.30.38]}def survey(results, category_names):
""" Parameters ---------- results : dict A mapping from question labels to a list of answers per category. It is assumed all lists contain the same number of entries and that it matches the length of *category_names*. category_names : list of str The category labels. """
labels = list(results.keys())
data = np.array(list(results.values()))
data_cum = data.cumsum(axis=1)
category_colors = plt.get_cmap('RdYlGn')(
np.linspace(0.15.0.85, data.shape[1]))
fig, ax = plt.subplots(figsize=(9.2.5))
ax.invert_yaxis()
ax.xaxis.set_visible(False)
ax.set_xlim(0, np.sum(data, axis=1).max())
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
widths = data[:, i]
starts = data_cum[:, i] - widths
ax.barh(labels, widths, left=starts, height=0.5,
label=colname, color=color)
xcenters = starts + widths / 2
r, g, b, _ = color
text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
for y, (x, c) in enumerate(zip(xcenters, widths)):
ax.text(x, y, str(int(c)), ha='center', va='center',
color=text_color)
ax.legend(ncol=len(category_names), bbox_to_anchor=(0.1),
loc='lower left', fontsize='small')
return fig, ax
survey(results, category_names)
plt.show()
Copy the code
Pie (data, explode=None, labels=None, colors=None, autopct=None..)
fig, ax = plt.subplots(figsize=(8.4), subplot_kw=dict(aspect="equal"))
recipe = ["375 g flour"."75 g sugar"."250 g butter"."300 g berries"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[- 1] for x in recipe]
def func(pct, allvals):
absolute = int(pct/100.*np.sum(allvals))
return "{:.1f}%\n({:d} g)".format(pct, absolute)
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
ax.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1.0.0.5.1))
plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Matplotlib bakery: A pie")
plt.show()
Copy the code
3.2.6 Histogram hist(data, bins=None, range=None, density=None, weights=None…)
np.random.seed(19680801)
# Sample data
mu = 100 The mean #
sigma = 15 # standard deviation
x = mu + sigma * np.random.randn(437)
num_bins = 50
fig, ax = plt.subplots()
# Draw the histogram
n, bins, patches = ax.hist(x, num_bins, density=1)
# Best fit line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
np.exp(0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, "--")
ax.set_xlabel("智商")
ax.set_ylabel(Probability density)
ax.set_title("IQ histogram: Mean =100, standard deviation =15")
Adjust spacing to prevent yLabel from being occluded
fig.tight_layout()
plt.show()
Copy the code
3.2.7 2-d histogram: HIST2D (x, Y, bins=10, range=None, density=False, weights=None,…)
import matplotlib.colors as mcolors
from numpy.random import multivariate_normal
data = np.vstack([
multivariate_normal([10.10], [[3.2], [2.3]], size=100000),
multivariate_normal([30.20], [[2.3], [1.3]], size=1000)
])
gammas = [0.8.0.5.0.3]
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8.6))
axes[0.0].set_title('Linear normalization')
axes[0.0].hist2d(data[:, 0], data[:, 1], bins=100)
for ax, gamma in zip(axes.flat[1:], gammas):
ax.set_title(R 'Power law $$' (\ gamma = % 1.1 f) % gamma)
ax.hist2d(data[:, 0], data[:, 1],
bins=100, norm=mcolors.PowerNorm(gamma))
fig.tight_layout()
plt.show()
Copy the code
3.2.8 Displaying pictures: imshow(X)
with open('dog.jpeg'.'rb') as image_file:
image = plt.imread(image_file)
fig, ax = plt.subplots()
ax.imshow(image)
ax.set_title("Hi, we meet again!")
ax.axis('off')
plt.show()
Copy the code
3.3 the axis
Although axis and axes mean axis in Chinese translation, axes is more like the coordinate space formed by axis. As introduced above, we can draw various images and display pictures in this coordinate space. If axes were “axis” in the abstract sense, then axis would be the real coordinate axis; In a 2-d plot, there are only two axes the horizontal axis x and the vertical axis y. Since Axis forms part of Axes, we can use the axes object’s methods to set the attributes for x and y.
figure, axes = plt.subplots(1.2, figsize=(6.3))
ax1, ax2 = axes
# Set the coordinate display interval
xmin, xmax, ymin, ymax = 0.10.50.100
ax1.axis([xmin, xmax, ymin, ymax])
# hidden axis
ax2.set_axis_off()
ax2.set_title("axis off.")
plt.show()
Copy the code
3.4 artist
The Chinese translation for artist is artist, which in Matplotlib has a more general meaning, that all visible elements are artists. Such as: title, Legend, Grid, Axis, TICK, label, text and so on.
np.random.seed(19680801)
data = np.random.randn(2.100)
fig, axs = plt.subplots(2.2, figsize=(5.5))
axs[0.0].hist(data[0])
axs[1.0].scatter(data[0], data[1])
axs[0.1].plot(data[0], data[1])
axs[1.1].hist2d(data[0], data[1])
plt.show()
Copy the code
Guess you like
- [1] The foundation of Scientific computation in Python, Numpy
- [2] Python Data Analysis Toolkit pandas
Writing a column is not easy, so if you find this article helpful, give it a thumbs up. Thanks for your support!
- Personal website: Kenblog.top
- Github site: kenblikylee.github. IO
Wechat scan qr code to obtain the latest technology original