当前位置:网站首页>Four pictures to understand some basic usage of Matplotlib
Four pictures to understand some basic usage of Matplotlib
2022-04-23 08:54:00 【Icy Hunter】
Actually matplotlib The picture is not so ugly , Especially the first one , It feels acceptable ( It looks a little ugly because there are too many things
The code is as follows :
# coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
mpl.rcParams['font.sans-serif'] = ['FangSong'] # Specify Chinese font
mpl.rcParams['axes.unicode_minus'] = False # Resolve save image is negative '-' Questions displayed as squares
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # The minus sign is displayed normally
fig = plt.figure(figsize=(10, 20), dpi=100) # Resize canvas , clarity
fig1 = fig.add_subplot(221) # canvas 1
fig2 = fig.add_subplot(222) # canvas 2
fig3 = fig.add_subplot(223) # canvas 3
fig4 = fig.add_subplot(224) # canvas 4
def draw_fig1():
# fig1
x = np.linspace(0, 5 * np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = x
# x Axis to y1 Fill the area with
fig1.fill(x, y1, 'b', alpha=0.5, label="sin(x)")
fig1.plot(x, y2, 'r', alpha=0.5, label="cos(x)")
fig1.scatter(x, y3, alpha=0.8, label="scatter")
# y1 +1 1 Region , And y1 > 0 Fill the area with
fig1.fill_between(x, y1 + 1, y1 - 1, where=y1 > 0, facecolor='b', alpha=0.2)
fig1.grid(True)
# fig1.set_ylim(bottom=-10, top=10) # Set up x scale
# fig1.set_xlim(left=0, right=10, emit=1)
fig1.set_title(" Fill in the picture ")
fig1.set_xlabel("x Axis ", fontsize=10, labelpad=10) # The size of the word and the distance from the inner axis
fig1.set_ylabel("y Axis ", fontsize=10, labelpad=10)
fig1.set_xticks([1, 2, 3])
fig1.set_xticklabels(["A", "B", "C"], rotation=30, fontsize=10) # Set up x Axis coordinates
# fig1.set_yticks([-1, 1, 0, 0.1])
fig1.legend(fontsize=10, loc="center") # Show Legend
# loc Take (‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’,
# ‘center left’, ‘center , right’, ‘lower center’, ‘upper center’, ‘center’)
def draw_fig2():
import numpy as np
import matplotlib.pyplot as plt
# The pie chart is divided into five parts , Value of each
z = [10, 20, 30, 40, 50]
# The proportion that the corresponding block deviates from the center of the circle
explode = [0, 0.2, 0, 0, 0]
# The corresponding content of each piece
labels = ('A', 'B', 'C', 'D', 'E')
colors = ["r", "g", "b", "y", "pink"]
# pie(x, explode=None, labels=None, colors=None, autopct=None,
# pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
# radius=None, hold=None)
# x: The number of pie charts , And the value of each piece
# explode: The proportion that the corresponding block deviates from the center of the circle
# labels: The label of each piece
# colors: It's also an array , Represents the color of each piece of content
# autopct: It shows the proportion of each block
# pctdistance=0.8: The percentage of the distance between the label and the center
# shadow=True: Whether there is a shadow effect
# labeldistance: Indicates that the distance from the center point of each corresponding content text is a multiple of the pie chart radius
# startangle=90 Start drawing angle , And it's drawn counterclockwise
# radius: Radius of pie chart , The default is 1 hold: Whether to overwrite other graphics , If in a figure Draw in , choice True Will be covered ,False Will coexist
fig2.pie(z, explode=explode, labels=labels, startangle=90, autopct='%1.1f%%',
colors=colors, shadow=True, pctdistance=0.8, labeldistance=1.2)
fig2.legend()
def draw_fig3():
data = np.random.randint(100, size=(1, 100))[0]
data[99] = 300
fig3.boxplot(data)
fig3.set_xlabel(" features ")
def draw_fig4():
key_name = ["A", "B", "C", "D", "E"]
key_values = [0.1, 0.9, 1, 1, -0.5]
def auto_label(rects):
for rect in rects:
height = rect.get_height()
if height >= 0:
# Mark the number on the corresponding column
fig4.text(rect.get_x() + rect.get_width() / 2.0 - 0.3, height + 0.02, '%.3f' % height)
else:
fig4.text(rect.get_x() + rect.get_width() / 2.0 - 0.3, height - 0.06, '%.3f' % height)
# If there is less than 0 The numerical , Then draw 0 Scale horizontal straight line
fig4.axhline(y=0, color='black')
# normalization , Let the colors be evenly distributed
norm = plt.Normalize(-1, 1)
norm_values = norm(key_values)
map_vir = cm.get_cmap(name='viridis') # Get the style of the corresponding color mapping bar
colors = map_vir(norm_values) # The mapping bar should be mapped to the data
ax = fig4.bar(key_name, key_values, width=0.5, color=colors, edgecolor='white') # Set the color of the box border
sm = cm.ScalarMappable(cmap=map_vir, norm=norm) # norm Set max min
plt.colorbar(sm)
auto_label(ax)
bwith = 4 # The border width is set to 2
TK = plt.gca() # Get border
TK.spines['bottom'].set_linewidth(bwith) # Lower edge of frame
TK.spines['left'].set_linewidth(bwith) # Frame left
TK.spines['top'].set_linewidth(bwith) # On the frame
TK.spines['right'].set_linewidth(bwith) # On the right side of the frame
draw_fig1()
draw_fig2()
draw_fig3()
draw_fig4()
plt.savefig(" Four pictures .png", dpi=100)
plt.show()
版权声明
本文为[Icy Hunter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230815306072.html
边栏推荐
- Chris LATTNER, father of llvm: the golden age of compilers
- 使用flask和h5搭建网站/应用的简要步骤
- Single chip microcomputer nixie tube stopwatch
- PLC的点表(寄存器地址和点表定义)破解探测方案--方便工业互联网数据采集
- 四张图弄懂matplotlib的一些基本用法
- Withholding agent
- Illegal character in scheme name at index 0:
- BK3633 规格书
- Go语言自学系列 | golang结构体作为函数参数
- Go语言自学系列 | golang方法
猜你喜欢
Bk3633 specification
ONEFLOW learning notes: from functor to opexprinter
Idea package jar file
The crawler returns null when parsing with XPath. The reason why the crawler cannot get the corresponding element and the solution
php基于哈希算法出现的强弱比较漏洞
Arbre de dépendance de l'emballage des ressources
论文阅读《Multi-View Depth Estimation by Fusing Single-View Depth Probability with Multi-View Geometry》
共享办公室,提升入驻体验
OneFlow學習筆記:從Functor到OpExprInterpreter
L2-024 tribe (25 points) (and check the collection)
随机推荐
Virtual online exhibition - Online VR exhibition hall realizes 24h immersive exhibition viewing
深度学习框架中的自动微分及高阶导数
Bk3633 specification
Whether the same binary search tree (25 points)
1099 建立二叉搜索树 (30 分)
Automatic differentiation and higher order derivative in deep learning framework
Use include in databinding
Summary of solid problems
怎样读取Excel表格到数据库
MATLAB 画五星红旗
Idea import commons-logging-1.2 Jar package
DJ音乐管理软件Pioneer DJ rekordbox
[indexof] [lastIndexOf] [split] [substring] usage details
L2-022 rearrange linked list (25 points) (map + structure simulation)
Arbre de dépendance de l'emballage des ressources
Go language self-study series | golang method
Go language self-study series | golang structure as function parameter
Latex mathematical formula
Learn SQL injection in sqli liabs (Level 11 ~ level 20)
关于cin,scanf和getline,getchar,cin.getline的混合使用