当前位置:网站首页>Use Matplotlib to draw a preliminary chart
Use Matplotlib to draw a preliminary chart
2022-07-02 08:08:00 【Villanelle#】
Required libraries
matplotlib
In bagpyplot
modular , For drawing .numpy
modular , Used to complete numerical operations 、 Matrix operations, etc .pandas
modular , For data manipulation and analysis 、 Import data files, etc .
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
notes : All project examples in this article are in Jupyter Notebook
Operating in the environment .
Draw a curve plot
General steps
plt.figure
Specify the image display scale and pixels
# Specify the image display scale and pixels 5*3 Every unit 200 Pixels , namely 1000*600
plt.figure(figsize=(5,3), dpi=200)
plt.style.use
Customize canvas style
# Customize canvas style
plt.style.use('seaborn-whitegrid')
plt.plot
Draw curve line
# Draw curve line , You can set the legend 、 Color 、 Line width 、 Marker points 、 Mark point size 、 Mark point edge color 、 Line type, etc
plt.plot(x, y, label='blue', color='#6699ff', linewidth=4, marker='.', markersize=20, markeredgecolor='#3333ff', linestyle='-.')
# Can pass fmt = '[marker][line][color]' Quickly set the marking point 、 Linetype and color , But be careful before keyword parameters
plt.plot(x, z, 'g^-.', label='green')
plt.title
plt.xlabel
plt.ylabel
Set chart title and axis title
# Set chart title , You can set the title font 、 Font size ( The dictionary form )
plt.title("First graph!",fontdict={
'fontname':'Comic Sans MS','fontsize':20})
# Set the axis title , You can set the axis font 、 Font size ( The dictionary form )
plt.xlabel("X Axis",fontdict={
'fontname':'Times New Roman','fontsize':10})
plt.ylabel("Y Axis",fontdict={
'fontname':'Times New Roman','fontsize':10})
plt.xticks
plt.yticks
Set up x,y Axis scale point
# Set up x Axis scale point
plt.xticks([1,2,3,4,5])
# Set up y Axis scale point
plt.yticks([2,3,4,5,6,7])
plt.legend()
Show Legend ( namelyplt.plot
Medium label)
# Show Legend
plt.legend()
plt.savefig
Save the picture
# Save the picture
plt.savefig('firstgraph.png',dpi=200)
plt.show
Display images
# Display images
plt.show()
Other commonly used numpy
Method
np.linspace(start, stop, num=50)
Generate an array at equal intervals according to the start and end data , from start Start to stop end , common num A little bit ( Default 50 individual ).np.sin(array)
Calculate the sine of the array , Returns an array .
x = np.linspace(0, 10, 1000)
plt.plot(x,np.sin(x),'b--')
plt.show()
np.arange(start, stop, step)
Andnp.linspace()
similar , Generate an array at equal intervals according to the start and end data , But it is often used for step value step When known .
x2 = np.arange(0, 4.5, 0.5)
# Piecewise functions
plt.plot(x2[:6], x2[:6]**2, 'b.-', label='x1')
plt.plot(x2[5:], x2[5:]**2, 'b.:', label='x2')
plt.legend()
plt.show()
Draw a column chart bar chart
General steps
plt.figure
Specify the image display scale and pixels
# Specify the image display scale and pixels
plt.figure(figsize=(6,4),dpi=200)
plt.style.use
Customize canvas style
# Customize canvas style ( Default )
plt.style.use('default')
- Set column name list and corresponding value list
labels = ['A','B','C']
values = [1, 4, 2]
plt.bar
Draw the column
# Draw a column diagram and pass it to bars,bars[0] It means the first column
bars = plt.bar(labels, values)
bar.set_hatch
Set the column pattern
# Set the histogram pattern
patterns = ['*','/','O']
for bar in bars:
bar.set_hatch(patterns.pop(0))
plt.title
Set the histogram Title
# Set the histogram Title
plt.title("My Bars")
plt.savefig
Save the picture
# Save the picture
plt.savefig('bar.png',dpi=200)
plt.show
Display images
# Display images
plt.show()
Draw the pie chart pie chart
General steps
pd.read_csv()
Reading data ( It's used herepandas
Method of library ) Return to table
fifa = pd.read_csv('fifa_data.csv')
fifa.head(5) # View the data of the first five rows
plt.figure
Specify the image display scale and pixels
# Specify image pixels
plt.figure(dpi=200)
plt.style.use
Customize canvas style
# Customize canvas style
plt.style.use('ggplot')
fifa.loc[]
Set conditions , Filter data , Return to table ( Remove the lines that do not meet the conditions )fifa.loc[...].count
Get the number of rows that meet the condition ( At this time, we only get the number of rows in each column , Need index 0 Subscripts get int Type line number )
# Set conditions , Filter data
left = fifa.loc[fifa['Preferred Foot'] == 'Left'].count()[0]
right = fifa.loc[fifa['Preferred Foot'] == 'Right'].count()[0]
- Enter label parameters 、 Color parameters 、 Explosion parameters (0~1, The bigger it is, the farther it is from the center ) etc.
# Tag parameters
labels=['Left','Right']
# Color parameters
colors=['#0099ff','#ff6699']
# Explosion parameters
explode=(0.2, 0)
plt.pie
Draw the pie chart , Include label 、 Color and explosion parameters , Include the distance from the center point in the number (0~1, The bigger it is, the farther it is from the center ), Contains the number of decimal places displayed by default
# Draw the pie chart , The default display is two decimal places plus %( Escape characters are used here %%)
plt.pie([left, right],labels=labels, colors=colors, explode=explode, pctdistance=0.7, autopct='%.2f%%')
plt.title
Set pie chart title
# Set pie chart title
plt.title("Foot Preference of FIFA Players")
plt.legend()
Show Legend ( namely label)
# Show Legend
plt.legend()
plt.savefig
Save the picture
# Save the picture
plt.savefig('bar.png',dpi=200)
plt.show
Display images
# Display images
plt.show()
Draw a histogram hist
General steps
pd.read_csv()
Reading data ( It's used herepandas
Method of library ) Return to tableplt.figure
Specify the image display scale and pixels- Enter the range of boxes
plt.figure(figsize=(8,5), dpi=200)
plt.hist
Draw a histogram , Given the detected columns and boxes , The histogram will be automatically generated
plt.hist(fifa.Overall, bins=bins, color='#33ccff')
plt.title
plt.xlabel
plt.ylabel
Set chart title and axis title
plt.title("Distribution of Player Skills in FIFA")
plt.xlabel("Number of Players")
plt.ylabel("Skill Level")
plt.xticks
Set up x Axis scale point
plt.xticks(bins)
plt.savefig
Save the picture
# Save the picture
plt.savefig('bar.png',dpi=200)
plt.show
Display images
# Display images
plt.show()
边栏推荐
- 解决jetson nano安装onnx错误(ERROR: Failed building wheel for onnx)总结
- Open3d learning note 3 [sampling and voxelization]
- [binocular vision] binocular correction
- C # connect to MySQL database
- On the back door of deep learning model
- Carsim problem failed to start Solver: Path Id Obj (X) was set to y; Aucune valeur de correction de xxxxx?
- 关于原型图的深入理解
- 业务架构图
- Eklavya -- infer the parameters of functions in binary files using neural network
- 樂理基礎(簡述)
猜你喜欢
Using super ball embedding to enhance confrontation training
Sequence problem for tqdm and print
图像增强的几个方法以及Matlab代码
[learning notes] numerical differentiation of back error propagation
Specification for package drawing
OpenCV3 6.2 低通滤波器的使用
In the era of short video, how to ensure that works are more popular?
【Batch】learning notes
Income in the first month of naked resignation
Using transformer for object detection and semantic segmentation
随机推荐
Global and Chinese markets for Salmonella typhi nucleic acid detection kits 2022-2028: Research Report on technology, participants, trends, market size and share
【MobileNet V3】《Searching for MobileNetV3》
Jupyter Notebook常用快捷键(在命令模式中按H也可查看)
(15) Flick custom source
The hystrix dashboard reported an error hystrix Stream is not in the allowed list of proxy host names solution
Fundamentals of music theory (brief introduction)
w10升级至W11系统,黑屏但鼠标与桌面快捷方式能用,如何解决
EKLAVYA -- 利用神经网络推断二进制文件中函数的参数
用全连接层替代掉卷积 -- RepMLP
Cvpr19 deep stacked hierarchical multi patch network for image deblurring paper reproduction
使用Matplotlib绘制图表初步
[learning notes] matlab self compiled image convolution function
力扣方法总结:滑动窗口
One book 1078: sum of fractional sequences
Principes fondamentaux de la théorie musicale (brève introduction)
力扣每日一题刷题总结:字符串篇(持续更新)
Open3d learning note 4 [surface reconstruction]
力扣方法总结:查找类
install. IMG production method
多站点高可用部署