当前位置:网站首页>Matplotlib swordsman line - first acquaintance with Matplotlib
Matplotlib swordsman line - first acquaintance with Matplotlib
2022-07-02 09:13:00 【Qigui】
Individuality signature : The most important part of the whole building is the foundation , The foundation is unstable , The earth trembled and the mountains swayed . And to learn technology, we should lay a solid foundation , Pay attention to me , Take you to firm the foundation of the neighborhood of each plate .
Blog home page : Qigui's blog
Included column :Python The Jianghu cloud of the three swordsmen
From the south to the North , Don't miss it , Miss this article ,“ wonderful ” May miss you yo
Triple attack( Three strikes in a row ):Comment,Like and Collect—>Attention
List of articles
Matplotlib brief introduction
know Matlpotlib
- Matplotlib yes Python Of 2D Drawing library , It makes it easy for users to graph data , And provide a variety of output formats .
- Matplotlib It can be used to draw all kinds of static , dynamic , Interactive charts , We know Seaborn,Pandas The drawing interface is also based on Matplotlib More advanced packaging .
- Matplotlib It's a very powerful one Python drawing tools , We can use this tool to present a lot of data more intuitively in the form of charts .
- Matplotlib You can draw a line diagram 、 Scatter plot 、 Contour map 、 Bar chart 、 Histogram 、3D graphics 、 Even graphic animation and so on .
install Matplotlib library
- Use pip
pip install matplotlib
- Use conda
conda install matplotlib
- Install the official version
https://matplotlib.org/stable/users/installing/index.html
Take a simple chestnut
- introduce Matplotlib And named it plt, Note that this introduces matplotlib.pyplot Instead of introducing matplotlib.
- Matplotlib The image is drawn on figure( Such as windows,jupyter forms ) Upper , every last figure It also contains one or more axes( A sub region that can specify a coordinate system ).
- Simplest creation figure as well as axes The way is through pyplot.subplots command , establish axes in the future , have access to Axes.plot Draw the simplest line chart .
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
Output graph :
Matplotlib Chart window
- Matplotlib → One python Version of matlab Drawing interface , With 2D Mainly , Support python、numpy、pandas Basic data structure , Efficient operation and rich chart Library .
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# This show() The main method is to display the drawn graphics , When we finish drawing the figure , You can call this method .
# Chart window 1 → plt.show()
plt.plot(np.random.rand(10))
plt.show()
# Directly generate charts
# Chart window 2 → Magical function , Embed chart
# adopt Jupyter My magic command %matplotlib inline Can be directly in jupyter notebook Show the chart in , You don't need to use every chart plt.show() To show
% matplotlib inline
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)
# Directly embedded in the chart , no need plt.show()
# <matplotlib.collections.PathCollection at ...> Represents the chart object
# Chart window 3 → Magical function , Pop up interactive matplotlib window
% matplotlib notebook
s = pd.Series(np.random.randn(100))
s.plot(style = 'k--o',figsize=(10,5))
# Interconvertible matplotlib window , no need plt.show()
# It can be adjusted
# Chart window 4 → Magical function , eject matplotlib Console
% matplotlib qt5
df = pd.DataFrame(np.random.rand(50,2),columns=['A','B'])
df.hist(figsize=(12,5),color='g',alpha=0.8)
# Interactive console
# If the display mode has been set ( such as notebook), You need to restart and then run the magic function
# Interactive Windows Embedded in web pages and Console , Only one
#plt.close()
# close window
#plt.gcf().clear()
# Empty the contents of the chart every time
Part of the diagram
A complete matplotlib Images usually include the following four levels , These layers are also called containers (container)
- Figure: Top level , To hold all drawing elements
- Axes:matplotlib The core of the universe , Contains a large number of elements to construct a subgraph , One figure It can be composed of one or more subgraphs
- Axis:axes The subordinate level of , It's used to deal with all coordinates and axes , Grid related elements
- Tick:axis The subordinate level of , It's used to deal with all the elements related to the scale
Figure
The easiest way to create a new drawing is to use pyplot:
- adopt plt.subplot() Command to create Figure and Axes
- axes Is the coordinate system of the drawing
- figure Is the drawing window
fig = plt.figure() # An empty figure without an axis
fig, ax = plt.subplots() # Uniaxial graph , Create one that contains a axes Of figure
fig, axs = plt.subplots(2, 2) # have 2x2 Graph of axis grid
Axes
Axis object ( Pay attention to differences stay Axes and Axis ) Provide scales and scale labels Provide the scale for the data in the axis . Every Axes also Yes :
- A title ( By setting set_title())
- One x label ( By setting set_xlabel())
- One y The tag set passes set_ylabel()).
Axis
These objects set scales and limits and generate scales ( Mark On shaft ) And scale labels ( String marking the scale ).
Artist
Everything visible on the picture is an artist ( even to the extent that Figure, Axes, and Axis object ). When the graph is rendered , be-all Artists are canvas . Most artists are tied to a shaft ; In this way Artists cannot be shared by multiple axes , Nor can it move from one axis to another .
Input type of drawing function
numpy.array or numpy.asarray
- Drawing function expectation numpy.array perhaps numpy.ma.masked_array As Input , Or it can be passed to the object numpy.asarray. A class similar to an array ,
- for example pandas Data objects and numpy.matrix May not work as expected . The common agreement is to convert these into numpy.array Objects before painting .
- for example , To convert a numpy.matrix. The code is as follows :
b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)
dict 、 numpy.recarray, or pandas.DataFrame
- Most methods will also resolve addressable objects , for example dict 、 numpy.recarray, or pandas.DataFrame. Matplotlib Allow this data Keyword parameters and generate a graph of passing strings Corresponding to x and y Variable .
np.random.seed(19680801) # seed the random number generator.
data = {
'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b');
Two drawing interfaces
OO style
- Create graphics explicitly (figure) And axis (axes), And call methods on them , Also known as OO Pattern (object-oriented style)
- adopt plt.subplot() Command to create Figure and Axes, And then to axes Data binding
x = np.linspace(0, 2, 100) # Sample data
# Be careful , Even in OO In style , We also use it 'pyplot.figure' To create a drawing
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(x, x, label='linear') # stay x,y Draw some data on the axis
ax.plot(x, x**2, label='quadratic') # stay x,y Draw more data on the axis
ax.plot(x, x**3, label='cubic') # There are more
ax.set_xlabel('x label') # take x Add labels to the shaft
ax.set_ylabel('y label') # take y Add labels to the shaft
ax.set_title("Simple Plot") # Add title to axis
ax.legend(); # Add a legend
Output graph :
pyplot style
- rely on pyplot Automatically create and manage figure and axes, And the use of pyplot Function to plot
- There is also a simpler way to create ,matplotlib.pyplot Methods can be used directly in the current axes Draw an image on , If the user does not specify axes,matplotlib Will help you automatically create a .
x = np.linspace(0, 2, 100) # Sample data
plt.figure(figsize=(5, 2.7))
plt.plot(x, x, label='linear') # stay x,y Draw some data on the axis .
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
Output graph :
General drawing template
OO Drawing template
import matplotlib.pyplot as plt
import numpy as np
# 1 Prepare the data
x = np.linspace(0, 2, 100)
y = x**2
# 2 Set the drawing style , This step is not necessary , The style can also be set in the drawing image
mpl.rc('lines', linewidth=4, linestyle='-.')
# 3 Define the layout
fig, ax = plt.subplots()
# 4 The plot
ax.plot(x, y, label='linear')
# 5 Add tags , Text and legend
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title("Simple Plot")
ax.legend()
Output graph :
pyplot Drawing template
import matplotlib.pyplot as plt
import numpy as np
# 1 Prepare the data
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
# 2 Define the image window
plt.figure(num=3, figsize=(8, 5))
# 3 drawing
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# 4 Define the coordinate axis range and name
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
# 5 Define axis scale and name
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# 6 Set the image border color
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 7 Adjust the scale and border position
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
边栏推荐
- 盘点典型错误之TypeError: X() got multiple values for argument ‘Y‘
- 汉诺塔问题的求解与分析
- 统计字符串中各类字符的个数
- Micro service practice | introduction and practice of zuul, a micro service gateway
- win10使用docker拉取redis镜像报错read-only file system: unknown
- Pyspark de duplication dropduplicates, distinct; withColumn、lit、col; unionByName、groupBy
- QT -- how to set shadow effect in QWidget
- C call system sound beep~
- 队列的基本概念介绍以及典型应用示例
- 微服务实战|Eureka注册中心及集群搭建
猜你喜欢
MYSQL安装出现问题(The service already exists)
Chrome视频下载插件–Video Downloader for Chrome
Sentinel reports failed to fetch metric connection timeout and connection rejection
Hengyuan cloud_ Can aiphacode replace programmers?
[go practical basis] how to set the route in gin
[staff] the lines and spaces of the staff (the nth line and the nth space in the staff | the plus N line and the plus N space on the staff | the plus N line and the plus N space below the staff | the
京东面试官问:LEFT JOIN关联表中用ON还是WHERE跟条件有什么区别
Minecraft plug-in service opening
A detailed explanation takes you to reproduce the statistical learning method again -- Chapter 2, perceptron model
一篇详解带你再次重现《统计学习方法》——第二章、感知机模型
随机推荐
Micro service practice | introduction and practice of zuul, a micro service gateway
[go practical basis] how to install and use gin
查看was发布的应用程序的端口
Image transformation, transpose
Multi version concurrency control mvcc of MySQL
CSDN Q & A_ Evaluation
gocv opencv exit status 3221225785
MYSQL安装出现问题(The service already exists)
1、 QT's core class QObject
Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers
使用递归函数求解字符串的逆置问题
Redis zadd导致的一次线上问题排查和处理
【Go实战基础】gin 高效神器,如何将参数绑定到结构体
双非本科生进大厂,而我还在底层默默地爬树(上)
C nail development: obtain all employee address books and send work notices
C# 百度地图,高德地图,Google地图(GPS) 经纬度转换
Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度
Ora-12514 problem solving method
微服务实战|原生态实现服务的发现与调用
The channel cannot be viewed when the queue manager is running