当前位置:网站首页>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
边栏推荐
- L2-3 romantic silhouette (25 points)
- Study notes of deep learning (8)
- PCTP考试经验分享
- LeetCode_DFS_中等_1254. 统计封闭岛屿的数目
- 1099 establish binary search tree (30 points)
- Notes d'apprentissage oneflow: de functor à opexprinterpreter
- Use of Arthas in JVM tools
- Go语言自学系列 | golang结构体作为函数参数
- Learn SQL injection in sqli liabs (Level 11 ~ level 20)
- MySQL查询两张表属性值非重复的数据
猜你喜欢

Enterprise wechat application authorization / silent login

Valgrind and kcache grind use run analysis

Multi view depth estimation by fusing single view depth probability with multi view geometry

LaTeX论文排版操作

STM32 uses Hal library. The overall structure and function principle are introduced

Solidity 问题汇总

请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨

Brief steps to build a website / application using flash and H5

LeetCode_DFS_中等_1254. 统计封闭岛屿的数目

Consensus Token:web3. 0 super entrance of ecological flow
随机推荐
Go语言自学系列 | golang方法
Idea is configured to connect to the remote database mysql, or Navicat fails to connect to the remote database (solved)
[58] length of the last word [leetcode]
Search tree judgment (25 points)
Initial experience of talent plan learning camp: communication + adhering to the only way to learn open source collaborative courses
LLVM之父Chris Lattner:编译器的黄金时代
Play with binary tree (25 points)
PLC的点表(寄存器地址和点表定义)破解探测方案--方便工业互联网数据采集
Latex mathematical formula
扣缴义务人
L2-3 romantic silhouette (25 points)
增强现实技术是什么?能用在哪些地方?
L2-3 浪漫侧影 (25 分)
LaTeX数学公式
Study notes of deep learning (8)
PLC point table (register address and point table definition) cracking detection scheme -- convenient for industrial Internet data acquisition
Go language self-study series | golang method
Go language self-study series | golang structure as function parameter
爬虫使用xpath解析时返回为空,获取不到相应的元素的原因和解决办法
Bk3633 specification