当前位置:网站首页>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
边栏推荐
- Yangtao electronic STM32 Internet of things introduction 30 steps notes 1. The difference between Hal library and standard library
- Bk3633 specification
- Correct method of calculating inference time of neural network
- Taxable income
- Redis Desktop Manager for Mac(Redis可视化工具)
- Single chip microcomputer nixie tube stopwatch
- cadence的工艺角仿真、蒙特卡洛仿真、PSRR
- LaTeX数学公式
- Notes on xctf questions
- STM32 uses Hal library. The overall structure and function principle are introduced
猜你喜欢

OneFlow学习笔记:从Functor到OpExprInterpreter

Use of Arthas in JVM tools

xctf刷题小记

GUI编程简介 swing

K210 learning notes (II) serial communication between k210 and stm32

使用flask和h5搭建网站/应用的简要步骤

Notes on 30 steps of introduction to Internet of things of yangtao electronics STM32 III. Explanation of new cubeide project and setting

The crawler returns null when parsing with XPath. The reason why the crawler cannot get the corresponding element and the solution

On time atom joins hands with oneos live broadcast, and the oneos system tutorial is fully launched

Automatic differentiation and higher order derivative in deep learning framework
随机推荐
STM32 uses Hal library. The overall structure and function principle are introduced
Experimental report on analysis of overflow vulnerability of assembly language and reverse engineering stack
Basic usage of synchronized locks
Test your machine learning pipeline
Restore binary tree (25 points)
Go语言自学系列 | golang结构体指针
Redis Desktop Manager for Mac(Redis可视化工具)
Pctp test experience sharing
Chris LATTNER, father of llvm: the golden age of compilers
idea底栏打开services
Please arrange star trek in advance to break through the new playing method of chain tour, and the market heat continues to rise
玩转二叉树 (25 分)
Swagger document export custom V2 / API docs interception
LLVM之父Chris Lattner:编译器的黄金时代
搜索树判断 (25 分)
是否同一棵二叉搜索树 (25 分)
Idea is configured to connect to the remote database mysql, or Navicat fails to connect to the remote database (solved)
Flink同时读取mysql与pgsql程序会卡住且没有日志
是否完全二叉搜索树 (30 分)
Go language self-study series | golang method