当前位置:网站首页>Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers
Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers
2022-07-02 09:07: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
Customize your objects
- There are two types of Artists: primitives and container
primitives( The basic elements )
- primitives Represents the standard graphic object we want to draw on the canvas :
- curve Line2D
- rectangular Rectangle
- written words Text
- Images AxesImage
container( Containers )
container( Containers ) Is where they are placed
- Axis Axis,
- Coordinate system Axes
- And graphics Figure
The purpose of this standard is to create a Figure, for example , Use this Figure Create one or more Axes perhaps Subplot example , And use Axes example Auxiliary methods to create primitives.
Object container
Figure Containers ( Figure container )
- Top containers Artist It's a matplotlib.figure.Figure, It contains Numbers . The background of the figure is Rectangle, It's stored in Figure.patch.
- When you add subgraphs ( add_subplot()) and Axis ( add_axes()) When arriving at the map , These will be attached to Figure.axes.
- The way to create them is as follows :
fig = plt.figure()
ax1 = fig.add_subplot(211) # Make a 2*1 Graph , Select the first 1 Subtext
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3]) # Positional arguments , The four numbers represent (left,bottom,width,height)
ax1
print(fig.axes) # fig.axes It contains subplot and axes Two instances
- Output results and images :
AxesSubplot:
[AxesSubplot:, <matplotlib.axes._axes.Axes object at 0x7f0768702be0>]

- Because the figure remains “current axes( Current axis )” To support pylab/pyplot state
- Therefore, you should not insert or remove directly from the axis list Axes , But use add_subplot() and add_axes() Insertion method and Axes.remove or Figure.delaxes() Delete method .
- however , Traversable Axes List or index it to access Axes Custom instances .
- This is an example of adding an axis mesh :
for ax in fig.axes:
ax.grid(True)
- Output image :

- The picture also has its own images, lines, patches and text attribute , You can use these attributes to add basic elements directly .
- But when you do this , The default coordinate system Figure Will only be in pixels ( among Usually not what you want ).
- If you use graphic level method to add Artists( for example , Use Figure.text To add text ), Then the default coordinate system will be “figure Coordinate system ”, among (0, 0) Is the lower left corner of the graph and (1, 1) Is the upper right corner of the graph .
- And all the Artists equally , You can control this coordinate system by setting Transform attributes .
- You can explicitly use “figure coordinate ” Set up Artist Convert to fig.transFigure:
import matplotlib.lines as lines
fig = plt.figure()
l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)
l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)
fig.lines.extend([l1, l2])
plt.show()
Output image :

Figure attribute :
- axes—— List of shaft instances ( Include Subplot)
- patch—— Rectangular background
- images——FigureImages patch list – For raw pixel display
- legends—— Legend instance list ( differ Axes.legends)
- texts—— List of text instances
Axes Containers ( Shaft container )
- this matplotlib.axes.Axes yes Matplotlib Center of The universe
- It contains the vast majority For drawing Artists
- And there are many auxiliary methods to create and add these in the diagram Artists To itself
- And auxiliary methods of access and modification Customize Artists.
- image Figure, It contains a Patch. For Cartesian coordinates ,patch It's a Rectangle; For polar coordinates ,patch It's a Circle
- This patch Property determines the shape of the drawing area 、 Background and border :
ax = fig.add_subplot()
rect = ax.patch # Rectangle instance
rect.set_facecolor('green')
Output image :

Axes Containers are used to create concrete graphics . Like drawing a curve , Histogram , It's all painted on it . So use plt.xx Draw all kinds of figures ( Like a bar chart , Histogram , Scatter plot, etc. ) All right. Axes Encapsulation .
Objects should not be added directly to Axes.lines perhaps Axes.patches list , because Axes There are some things to do when creating and adding Or something :
It's set up Artist in figure and axes Properties of
It sets the default Axes transformation ( Unless already set );
It checks for inclusion in Artist Update the data structure to control automatic scaling , So that the view limits can be adjusted to include the plotted data .however , You can create objects yourself and add them directly to Axes, for example add_line and add_patch.
There's a lot more Axes Used to create primitives Auxiliary method of , Artists And add them to their respective containers .
Axes attribute :
- Set up x and y Maximum and minimum values of the axis
- After setting the scale , We can also set x Axis and y Maximum and minimum values of the axis . Can pass set_xlim/set_ylim To achieve
- To add text
- Before adding text, we used annotate, But if you don't need to comment
- In fact, there is another simpler way , That's using text Method
- Draw Double y Axis
- Mapping 1 by : ax1
- adopt ax2 = ax1.twinx() clone ax1, To add secondary axes
- Mapping 2 by : ax2
- Another thing to note ,twinx perhaps twiny Method will return a share x Axis or y New shaft axes, If you pass plt.sublots Generate ax after , Then draw the diagram 2 when , need In this newly generated ax Draw on

- Set up x and y Maximum and minimum values of the axis
in addition Axes There are also two most important Artist container:
- ax.xaxis:XAxis Instance of object , Used for processing x Axis tick as well as label The draw
- ax.yaxis:YAxis Instance of object , Used for processing y Axis tick as well as label The draw
Axis Containers ( Shaft container )
this matplotlib.axis.Axis Case handling Calibration line 、 Gridlines 、 Scale labels and axis labels .
- You can have the y The axis is equipped with left and right scales , as well as x The upper and lower scales of the shaft .
- this Axis It is also stored for automatic scaling 、 Pan and zoom data_interval and view_interval
- as well as Locator and Formatter Examples of control positions and placement of tick marks
Axis It stands for x Axis or y Object of axis . contain Tick( scale ) object ,TickLabel Scale text object , as well as AxisLabel Axis text object .
axis Object has some methods to manipulate scales, text, etc .
Axis attribute :
- Set up x Axis and y Axis label The location of
- ax1.yaxis.set_label_coords(x,y)
- Set the scale format on the scale
- Display sub scale
- ax1.minorticks_on()
- Set up x Axis and y Axis label The location of
# Set the scale format on the scale
from matplotlib import ticker
formatter = ticker.FormatStrFormatter(" Custom format ")
ax1.yaxis.set_major_formatter(formatter)
Tick Containers ( Scale container )
- this matplotlib.axis.Tick Is our final container object from Figure To Axes To Axis To Tick The last object container in .
- this Tick Include scale And gridline instances , And the corresponding tag instance . Each of these can be accessed directly as an attribute Tick Of
- Tick attribute :
- Tick.tick1line:Line2D example
- Tick.tick2line:Line2D example
- Tick.gridline:Line2D example
- Tick.label1:Text example
- Tick.label2:Text example
- y The shaft is divided into left and right , therefore tick1 Corresponding to the axis on the left ;tick2 Corresponding to the axis on the right .
- x The shaft is divided into upper and lower , therefore tick1 Corresponding to the shaft on the lower side ;tick2 Corresponding to the shaft on the upper side .
- This is an example of setting the formatter for the right scale
- Dollar sign in y On the right side of the shaft and paint them green .
import numpy as np
import matplotlib.pyplot as plt
# Fix the random state to achieve reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
# Set up ticker The display format of
ax.yaxis.set_major_formatter('${x:1.2f}')
# Set up ticker Parameters of , The right side is the spindle , The color is green
ax.yaxis.set_tick_params(which='major', labelcolor='green',
labelleft=False, labelright=True)
plt.show()
- Output image :

边栏推荐
- Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
- Minecraft安装资源包
- Don't spend money, spend an hour to build your own blog website
- Qunhui NAS configuring iSCSI storage
- Pyspark de duplication dropduplicates, distinct; withColumn、lit、col; unionByName、groupBy
- Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度
- commands out of sync. did you run multiple statements at once
- gocv图片裁剪并展示
- [blackmail virus data recovery] suffix Hydra blackmail virus
- Loadbalancer dynamically refreshes Nacos server
猜你喜欢

Application of kotlin - higher order function

How to realize asynchronous programming in a synchronous way?

HackTheBox-Gunship

远程连接IBM MQ报错AMQ4036解决方法

Solution of Xiaomi TV's inability to access computer shared files

Minecraft空岛服开服

Qunhui NAS configuring iSCSI storage

commands out of sync. did you run multiple statements at once

Flink-使用流批一体API统计单词数量

【Go实战基础】gin 如何设置路由
随机推荐
Qt——如何在QWidget中设置阴影效果
【Go实战基础】gin 如何验证请求参数
WSL installation, beautification, network agent and remote development
Dip1000 implicitly tagged with fields
Minecraft空岛服开服
Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
Redis安装部署(Windows/Linux)
C#钉钉开发:取得所有员工通讯录和发送工作通知
Essay: RGB image color separation (with code)
Driving test Baodian and its spokesperson Huang Bo appeared together to call for safe and civilized travel
Gocv image reading and display
Minecraft install resource pack
C# 调用系统声音 嘀~
【Go实战基础】gin 如何设置路由
Linux二进制安装Oracle Database 19c
Openshift build image
一、Qt的核心类QObject
Move a string of numbers backward in sequence
QT drag event
Function ‘ngram‘ is not defined