当前位置:网站首页>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()
边栏推荐
- Brief introduction of prompt paradigm
- 常量指针和指针常量
- Global and Chinese market of medicine cabinet 2022-2028: Research Report on technology, participants, trends, market size and share
- Constant pointer and pointer constant
- STL速查手册
- Array and string processing, common status codes, differences between PHP and JS (JS)
- 我的vim配置文件
- 【雙目視覺】雙目矯正
- Jupyter Notebook常用快捷键(在命令模式中按H也可查看)
- 力扣每日一题刷题总结:栈与队列篇(持续更新)
猜你喜欢
Programmers can only be 35? The 74 year old programmer in the United States has been programming for 57 years and has not retired
Principes fondamentaux de la théorie musicale (brève introduction)
Target detection for long tail distribution -- balanced group softmax
用MLP代替掉Self-Attention
VS Code配置问题
静态库和动态库
CVPR19-Deep Stacked Hierarchical Multi-patch Network for Image Deblurring论文复现
How to back up the configuration before the idea when reinstalling the idea
Dynamic extensible representation for category incremental learning -- der
[learning notes] matlab self compiled image convolution function
随机推荐
用于类别增量学习的动态可扩展表征 -- DER
OpenCV3 6.2 低通滤波器的使用
Meta Learning 简述
Global and Chinese markets for Salmonella typhi nucleic acid detection kits 2022-2028: Research Report on technology, participants, trends, market size and share
Open3d learning note 4 [surface reconstruction]
Wang extracurricular words
Income in the first month of naked resignation
Matlab数学建模工具
Cvpr19 deep stacked hierarchical multi patch network for image deblurring paper reproduction
On the back door of deep learning model
Get the width and height of the screen in real time (adaptive)
Erase method in string
STM32疑难杂症之ST-LINK Connection error INVALID ROM TABLE
[learning notes] matlab self compiled image convolution function
One book 1078: sum of fractional sequences
Summary of solving the Jetson nano installation onnx error (error: failed building wheel for onnx)
On the confrontation samples and their generation methods in deep learning
Library function of C language
Sequence problem for tqdm and print
C语言的库函数