matplotlib basic chart drawing

Posted by Zanus on Wed, 29 Dec 2021 06:00:04 +0100

With Matplotlib, developers can generate graphs, histograms, power spectra, bar charts, error charts, scatter charts, etc. with only a few lines of code.
Matplotlib Basics
1. Elements included in the basic chart in Matplotlib
x-axis and y-axis
Horizontal and vertical axes
x-axis and y-axis scale
The scale marks the separation of coordinate axes, including the minimum scale and the maximum scale
x-axis and y-axis scale labels
Represents a value for a specific axis
Drawing area
Actual drawing area
2.hold attribute
The hold property is True by default, allowing multiple curves to be drawn in one graph; Change the hold attribute to False, and each plot will overwrite the previous plot.
However, it is not recommended to activate the hold property (there will be a warning). Therefore, use the default setting.
3. Gridlines
grid method
Use the grid method to add gridlines to the graph
Set the grid parameter (the parameter is the same as the plot function)
. lw stands for linewidth, the thickness of the line
. alpha indicates the light and shade of the line
4.axis method
If the axis method does not have any parameters, it returns the upper and lower limits of the current coordinate axis
5.xlim method and ylim method
Except PLT Axis method, you can also set the coordinate axis range through xlim and ylim methods
6.legend method
Two parameter transfer methods:
[recommended] add the label parameter to the plot function
Pass in a list of strings in the legend method
Configure the matplotlib parameter
Permanent configuration
matplotlib configuration information is read from the configuration file. In the configuration file, you can specify permanently valid default values for almost all attributes of matplotlib
Per installation configuration file
Python's site packages directory (site packages / Matplotlib / MPL data / matplotlibrc)
System level configuration. Each time matplotlib is reinstalled, the configuration file will be overwritten
If you want to maintain a persistent and effective configuration, it is best to set it in the user level configuration file
The best way to apply this profile is to use it as the default configuration template
User level matplotlib/matplotlibrc file (per user. matplotlib/matplotlibrc)
User's Documents and Settings directory
You can use Matplotlib get_ Configdir() command to find the configuration file directory of the current user
Current working directory
Directory where code runs
In the current directory, you can customize the matplotlib configuration item for the current project code contained in the directory. The file name of the configuration file is matplotlibrc
In Windows system, there is no global configuration file, and the location of user configuration file is C: \ documents and settings \ yourname matplotlib.
In Linux system, the location of global configuration file is / etc/matplotlibrc, and the location of user configuration file is $home / matplotlib/matplotlibrc.
Dynamic configuration
Configuration code in program
To finetune settings only for that execution; this overwrites every configuration file.
The priority of the configuration method is:
Matplotlib functions in Python code
matplotlibrc file in the current directory
User matplotlibrc file
Global matplotlibrc file
rcParams method
Access and modify all loaded configuration items through the rcParams dictionary

Line chart

import matplotlib.pyplot as plt
input_values=[1,2,3,4,5]
squares=[1,4,9,16,25]
plt.style.use('seaborn')
print(squares)
fig,ax= plt.subplots()
ax.plot(squares)
ax.plot(squares,linewidth=6)
ax.set_title("Square number",fontsize=24)
ax.set_xlabel("value",fontsize=14)
ax.set_ylabel("Square of value",fontsize=14)
ax.tick_params(axis='both',labelsize=14)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["axes.unicode_minus"]=False
fig.tight_layout()
plt.show()

Histogram

import pandas as pd
from matplotlib import pyplot as plt
hotdog = pd.read_csv(r"hot-dog-contest-winners.csv")
fig,ax=plt.subplots(figsize=(10,6))
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
x_data = hotdog['Year']
y_data = hotdog['Eaten']
plt.bar(x=x_data,height=y_data,color='b',edgecolor='k')
ax = plt.gca()
ax.set_title(u'Histogram of results of hot dog big stomach King competition in the past 30 years',fontproperties='SimHei',fontsize=14)
ax.set_xlabel('particular year')
ax.set_ylabel('Number of hot dogs eaten')
plt.show()

Scatter diagram

import pandas as pd
from matplotlib import pyplot as plt
postage=pd.read_csv(r"gdp-per-China-worldbank-1.csv")
fig,ax=plt.subplots(figsize=(10,6))
plt.scatter(postage["Year"],postage["GDP"],c='r',marker='o',alpha=0.5)
ax=plt.gca()
ax.set_title(u'1990-2020 China in GDP Variation scatter diagram',fontproperties='SimHei',fontsize=14)
ax.set_xlabel('particular year')
ax.set_ylabel('GDP')
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.show()

Bubble Diagram

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
crime = pd.read_csv("crimeRatesByState2005.csv")
crime2 = crime[crime.state != "United states"]
crime2 = crime2[crime2.state != "District of Columbia"]
s = list(crime2.population/10000)
colors = np.random.rand(len(list(crime2.murder)))
cm = plt.cm.get_cmap()
plt.scatter(x=list(crime2.murder),y=list(crime2.burglary),s=s,c=colors,cmap=cm,linewidth=0.5,alpha=0.5)
plt.xlabel("murder")
plt.ylabel("burglary")
plt.show()

Stairs

import pandas as pd
from matplotlib import pyplot as plt
postage=pd.read_csv(r"us-postage.csv")
fig,ax=plt.subplots(figsize=(10,6))
ax.step(postage["Year"],postage["Price"],where='post')
ax.set_title("US Postage Fee")
ax.set_xticks(postage["Year"])
ax.set_yticks([])
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["right"].set_visible(False)
for i,j in zip(postage["Year"],postage["Price"]):
    ax.text(x=i,y=j+0.003,s=j)
fig.tight_layout()
plt.show()

Pie chart

import matplotlib.pyplot as plt
import pandas as pd
timeData = pd.read_csv(r"doubledec.csv")
plt.figure(figsize=(9,9))
plt.title('Time pie chart of junior middle school students under the double reduction policy',fontdict={'fontsize':24},y=1.05)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
labels = ['sleep','at school ','homework','Free activities','Lunch dinner','Breakfast and others']
plt.pie(timeData['Time'],autopct='%1.1f%%',textprops={'fontsize':12,'color':'k'},labels=labels,startangle=90,counterclock=False)
plt.rcParams['legend.fontsize'] = 10
plt.legend(loc='lower left',frameon=False)
plt.axis('equal')
# tmp = [1]
# plt.pie(tmp,labels=[''],radius=0.5,colors='w')
plt.show()

Topics: Python matplotlib