Visualization-matplotlib (drawing of charts: line graphs, ring graphs, bar graphs, histograms, scatter graphs and bubble graphs, box graphs, polar graphs)

17 basic icon functions of pyplot

function Description
plt.plot (x, y, fmt, ……) Draw a graph
plt.boxplot(data,notch,position) Draw a box plot
plt.bar(left,height,width,bottom) Draw a bar graph
plt.bar(width,bottom,left,height) Draw a horizontal bar graph
plt.polar(theta,r) Draw polar coordinates
plt.pie(data, explode) Draw a pie chart
plt.psd(x,NFFT=256,pad_to,Fs) Plot the power spectral density
plt.specgram(x,NFFT=256,pad_to,Fs) Draw a spectrum
plt.cohere((x,y,NFFT=256,Fs)) Plot the correlation function of XY
plt.scatter(x,y) Draw a scatter plot, where x and y have the same length
plt.step(x,y,where) Draw a layout diagram
plt.hist(x,bin,normed) Draw a histogram
plt.contour(X,Y,Z,N) Draw contour maps
plt.vline () Draw a vertical graph
plt.stem (x, y, linefmt, markerfmt) Draw firewood diagram
plt.plot_date() Plot data date
Plt.plotfile () Write to file after drawing data

1. Line graph (plot function)

Data visualization (pylot function, Chinese display, text display, sub-drawing area)

2. Pie chart and ring chart

Pie chart concept: The
pie chart is used to indicate the proportions of different categories. Various categories are compared by the arc size. The pie chart divides a pie into multiple blocks according to the proportion of the classification. The entire pie represents the total amount of data. Each block (arc) represents the proportion of the category in the total.

Parameters of pie()

matplotlib.pyplot.pie(
        x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1,
        startangle=None, radius=None, counterclock=True,
        wedgeprops=None, textprops=None, center=(0, 0), frame=False,
        rotatelabels=False, *, data=None)

Common parameter section

x: Receive array, which represents the data used for drawing, no default.
explode: By default, the pie chart of x does not explode. Customize which piece of explosion & explosion distance.
labelsAnd labeldistance: By default, x has no label, and the label is located at 1.1 times the radius. Customize the label and position of each pie .
autopctAnd pctdistance: The default x does not display the percentage mark of each pie. Autopct custom is the percentage attribute of each pie , such as several decimal places, pctdistance displays the percentage at the radius of 0.6 by default, and customizes the percentage to the radius .
shadow: The default x is a two-dimensional flat pie chart without shadows. Whether the custom pie chart has a shadow attribute .
startangle: By default, the angle between the first slice of x and the horizontal plane is not fixed. Customize the angle of the first pie chart and the horizontal plane .
colors: Customize the color of each pie. By default, the system automatically sets the color of each pie .

Less commonly used parameter section

radius: The default x radius parameter is 1. The size of the custom radius , can be int | float.
counterclock: Customize the pointer direction , the default boolean value is True, which is arranged in reverse time for the x pie chart.
wedgeprops=dict(): Set some attributes of each pie chart. Among them, edgecolor='w' sets the border color to white, width=0.7 sets 0.3 times the radius of the pie chart to be blank, and linewidth=10 sets the thickness of the border to 10.
E.g:

explode = (0, 0.2, 0, 0)
ax1.pie(sizes, explode=explode, labels=laels, autopct='%.1f%%', pctdistance=0.7,  shadow=True, startangle=90,
        counterclock=False, wedgeprops=dict(edgecolor='w', width=0.7, linewidth=10))

Donut chart


#The so-called ring chart is to draw another pie chart smaller than the previous picture, and white, so the radius should be smaller plt.pie(sizes_0,radius=0.6,colors='w')#white inner circle

Code:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
labels = ['第一季度', '第二季度', '第三季度', '第四季度']
sizes=[13.8,22.8,53.3,39.8]
colors = ['tomato',  'goldenrod', 'green', 'y']
sizes_0=[1,0,0,0]#用于显示空心部分的各部分比例
explode = (0, 0.1, 0, 0) # 只爆炸第二块饼,爆炸距离是半径的0.1。
plt.subplot(1,2,1)#第一个饼图
#pctdistance默认在半径0.6位置显示百分数,自定义百分数距离半径的比例
plt.pie(sizes, explode=explode, labels=labels,colors=colors,autopct='%.2f%%', pctdistance=0.7, shadow=False, startangle=90,counterclock=False)
# 等价于 ax1.set(aspect='euqal'),使得饼图在figure窗口放大缩小的过程中,保持圆形不变。
plt.axis('equal')

plt.subplot(1,2,2)#第二个环形图
plt.pie(sizes,pctdistance=0.8,labels=labels,autopct='%.1f%%')
#所谓的环形图,就是再画一个比上个图小的饼图,并且为白色,所以半径要小
plt.pie(sizes_0,radius=0.6,colors='w')#白色内圈
plt.title("xxx")
plt.show()

examples

Insert picture description here

3. Histogram

import matplotlib.pyplot as plt;
plt.bar(   x,       # 元组或列表,数据的x坐标序列
        height,     # 元组或列表,数据序列
        width,      # 数值或列表,条形宽度,默认0.8
        bottom,     # 数值或列表,y轴的基准值,默认0
        align,      # 字符串,两种值可供选择{'center','edge'}
        color,      # 元组或列表,条形颜色
        edgecolor,  # 元组或列表,条边颜色
        linewidth,  # 元组或列表,可选条形边缘宽度,如为0则无边
        tick_label, # 元组或列表或字符串,条形数据的标签
        xerr,yerr,  # 元组或列表或数值,误差线
        ecolor,     # 元组或列表,误差线颜色,默认为黑色
        capsize,    # 误差线长度
        error_kw,   # 字典,错误条
        log,        # 布尔,是否以log对象做刻度,默认为假
        orientation # 字符串,两种值供选择{'vertical'垂直,'horizontal'水平}
        )

Insert picture description here
Insert picture description here
matplotlib.pyplot.barh (y, width, height=0.8, left=None, *, align='center', **kwargs) The
code in the above figure, the bar is changed to barh to get
Insert picture description here

4. Histogram

matplotlib.pyplot.hist(
x, bins=None, range=None, d ensity=False, weights=None, 
cumulative=False, bott om=None, histtype='bar', align='mid',
orientation= 'vertical', rwidth=None, log=False, color=None,
lab el=None, stacked=False, *, data=None, **kwargs)

x: Data set, the final histogram will make statistics on the data set
bins: Statistical interval distribution
range : tuple, the displayed interval, range takes effect when no bins are given
density: bool, the default is false, the frequency is displayed Statistics result, if True, the frequency statistics result will be displayed (frequency statistics result = number of intervals/(total number * interval width)). If stacked is also True, the sum of the histograms will be normalized to 1.
histtype: Optional one of {'bar','barstacked','step','stepfilled'}, the default is bar, it is recommended to use the default configuration, step uses a ladder shape, stepfilled will fill the ladder shape, The effect is similar to
bar⚫ align: one of {'left','mid','right'} can be selected, the default is'mid', which controls the horizontal distribution of the histogram, left or right, there will be some blank areas, it is recommended to use the default .
log: bool, the default is False, that is, whether the y-coordinate axis selects exponential scale
stacked: bool, the default is False, whether it is a stacked
graph⚫ orientation: optional {'vertical','horizontal'}, default'vertical'. If you set'horizontal', replace bar with barh
rwidth: floating point number or None, default None. Set the relative width of the histogram. If it is None, the width is automatically calculated. If histtype is set to'step' or'stepfilled', the parameter setting is ignored.

examples:

Insert picture description here
Insert picture description here

5. Scatter and bubble charts

matplotlib.pyplot.scatter(
x, y, s=None, c=None, marker=None, cmap=None, norm=None, 
vmin=None, vmax=None, alpha=None, linewidths=None, 
verts=<deprecated parameter>, edgecolors=None, *, plotnonfinite=False, 
data=None, **kwargs)

Common parameters are:
x,yThe coordinates
sof the scattered points; the area
cof the scattered points; the color of the scattered points (the default is blue'b');
markerthe mark
alphaof the scattered points; the transparency of the scattered points (a number between 0 and 1, 0 Is completely transparent, 1 is completely opaque);
linewidthsis the line width of the edge of the scatter;
if the marker is None, the value of verts is used to construct the scatter mark;
edgecolors is the edge color of the scatter.
Other parametersFor example, cmap is colormap; norm is data brightness; vmin, vmax and norm are used together to normalize brightness data, which are related to data brightness
Insert picture description here
Insert picture description here

6. Box diagram

pyplot.boxplot(x, notch=None, 
sym=None, vert= None, whis=None,
positions=None, widths=None, 
patch_artist=None,meanline=None, labels=None, ...)

x: Receive array. Represents the data used to draw the box plot. There is no default.
notch: Receive boolean. Show box plot in the form of a notch indicating whether it is a notch
sym: receiving a specific string. Specify the shape of the abnormal point. The default is None.
vert: Receive boolean. Indicates whether the graphic is horizontal, vertical or horizontal. The default is None.
meanline: Whether to express the mean value in the form of a line.
showmeans: Whether to display the mean value.
labels: Receive array. Specify the label for each boxplot. The default is None. showfliers:: Receive `boolean. Indicates whether to display abnormal values. The default is True.
examples:
Insert picture description here
Insert picture description here

7. Polar diagram

https://www.baidu.com/link?url=cCmHCVDOaJVpsP7KJpuxFXG5lSvK7MH0E8tA5TPB1t2cEbmX33VSraKmknVPycLfpn38bpvqk-xju9Ixd3JDLa&wd=&eqid=cc0e61050001d123000000065fd34646

Guess you like

Origin blog.csdn.net/weixin_46168350/article/details/111042434