matplot learning road three

1. Draw a rectangle (including square)
Draw a rectangle function Rectangle(xy, width, height, angle=0.0, kwargs), parameter description:
(1) xy, specify the coordinates of the left and bottom rectangles, represented by a tuple (x ,y), floating-point type.
(2) width, specify the width of the rectangle, floating point type.
(3) height, specify the height of the rectangle, floating point type.
(4) Angle, rotate the specified angle counterclockwise with xy coordinates as the base point (default is 0.0), and the unit symbol is °.
(5)
kwargs accepts key-value pair parameters, such as alpha=0.8 to set the transparency of the background color of the rectangle, linestyle=' --' to set the edge style of the rectangle

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3,3))   #为了确保正方形的长宽在屏幕显示一致,这里设置figure宽,高相等
axes = fig.add_subplot(1,1,1) 
square = plt.Rectangle((0.2,0.2),0.2,0.2,color='g',alpha=0.8)  #设置长宽为0.2的绿色正方形
square1 = plt.Rectangle((0.5,0.5),0.2,0.4,color='c',alpha=0.8,angle=60)  #c为青色逆时针旋转60度长方形
rectangle = plt.Rectangle((0.5,0.2),0.4,0.2,color='b',alpha=0.8,linestyle='--')  #蓝色带虚线边的长方形
axes.add_patch(square)  #必须用add_pathch()函数把绘制的图形加载到绘图区域,否则无法显示
axes.add_patch(square1)       
axes.add_patch(rectangle)
plt.show()

Insert picture description here

2. Draw a circle
Draw circle function Circle(xy, radius=5, **kwargs), parameter description:
(1) xy is the center coordinate.
(2) Radius is the length of the radius.
(3) **kwargs means that key-value pair parameters can be accepted. For example, alpha=0.5 specifies the transparency, facecolor='g' specifies the circle background color, edgecolor='r' specifies the round edge color, linestyle='-.' specifies the edge style, etc.
3. Draw an ellipse
Draw an ellipse function Ellipse(xy, width, height, angle=0, kwargs), parameter description:
(1) xy, set the ellipse center coordinates (x, y), floating point type.
(2) width, set the diameter of the x-axis of the ellipse.
(3) height, set the diameter of the y-axis of the ellipse.
(4) Angle, rotate the specified angle counterclockwise with xy coordinates as the base point (default is 0.0), and the unit symbol is °.
(5)
kwargs, accept key-value pair parameters, and use the same method as Rectangle().

from matplotlib.patches import Ellipse,Circle     #绘制圆,椭圆只能在pathches模块获取
fig = plt.figure()
axes = fig.add_subplot(1,1,1)
E1 = Ellipse(xy=(0.6,0.6),width=0.5,height=0.2,angle=30.0,facecolor='yellow',alpha=0.9)  #椭圆
C1 = Circle(xy=(0.2,0.2),radius=0.2,alpha=0.5)  #绘制一个圆
axes.add_patch(E1)
axes.add_patch(C1)
plt.show()

Insert picture description here
*4. Drawing polygons (triangles, parallelograms, trapezoids)
*Drawing polygon function Polygon(xy,closed=True,**kwargs), parameter description:
pair (x,y) coordinates.
*(3)**kwargs, accept key-value pair parameters, and use the same method as Rectangle().
*(1) xy, specify a numpy array with a shape of N×2, N refers to the number of coordinates, such as the triangle needs three
*(2) close, specify whether to close the polygon, when the value is False, the start point and the end point are the same.

import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.add_subplot(1,1,1)   #提供一个绘图子区域
p3 = plt.Polygon([[0.15,0.15],[0.15,0.7],[0.4,0.15]],color='k',alpha=0.5)   #三角形
p4 = plt.Polygon([[0.45,0.15],[0.2,0.7],[0.55,0.7],[0.8,0.15]],color='g',alpha=0.9)   #平行四边形
p5 = plt.Polygon([[0.69,0.45],[0.58,0.7],[0.9,0.7],[0.9,0.45]],color='b',alpha=0.9)   #梯形
axes.add_patch(p3)
axes.add_patch(p4)
axes.add_patch(p5)
plt.show()

Insert picture description here

1. Bar graph function
Function bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs), parameter description:
(1) x, bar x coordinate. , Including tuples, lists, arrays, etc.
(2) height, specify the height of the bar.
(3) width, set the width of the bar (default value: 0.8).
(4) bottom, set the y coordinate of the bar base (default value 0).
(5) align, set the position of the bar base,'center' sets the base to the x position,'edge' sets the left edge of the base to the x position, and sets the negative width and'edge' to align the right edge of the base with x .
(6) **kwargs, accept key-value pair parameters, such as color='g' to set the color of the bar, edgecolor='k' to set the color of the bar edge, linewidth=0.5 to set the width of the bar edge, tick_label=' The label at the top of the quantity bar graph, log=True sets the y-axis to logarithmic scale, orientation='horizontal' sets the horizontal bar graph ('vertical' vertical bar graph, the default value), alpha=0.9 sets the transparency, label='male' sets the bar graph column label, and left=1.5 sets the left alignment position of the bar graph base.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
plt.rc('font', family='simhei', size=15)  # 设置中文显示,字体大小15
plt.rc('axes', unicode_minus=False)  # 该参数解决负号显示问题
c = ['四年级', '五年级', '六年级']  # x轴刻度中文标签
x = np.arange(len(c)) * 0.8  # x轴刻度数,条形基座中间x位置数
girl = [19, 19, 21]  # 女生数量,对应条形高度
boy = [20, 18, 21]  # 男生数量,对应条形高度
b1 = plt.bar(x, height=girl, width=0.2, alpha=0.8,
             color='red', label='女生')  # 绘制女生数量红条形
b2 = plt.bar([x1+0.2 for x1 in x], height=boy, width=0.2,
             alpha=0.8, color='blue', label='男生')
plt.title('班级人数统计')
plt.legend()  # 显示图例(男生,女生)
plt.ylim(0, 40)  # 设置y轴(人数显示)的范围
plt.ylabel('人数')  # 设置y轴左边标签
plt.xticks([index + 0.2 for index in x], c)  # 设置x轴条形下面标签
plt.xlabel("班级")  # 设置x轴下面的标签
for r1 in b1:
    height = r1.get_height()  # 得到条形高度数
    plt.text(r1.get_x()+r1.get_width()/2, height+1,
             str(height), ha='center', va="bottom")  # 设置条顶值
for r2 in b2:
    height = r2.get_height()
    plt.text(r2.get_x()+r2.get_width()/2, height+1,
             str(height), ha='center', va='bottom')
plt.show()

Insert picture description here
**Histogram function
hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical ', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, kwargs), parameter description:
(1) x, a set of values, including tuples , List, array, etc., provide the number of probability samples.
(2) Bins, the number of bars, is to divide all the sample numbers into the range of the number of bars specified by bins for classification number statistics.
You can also specify the interval range of the bars, such as bins=[1,2,3,4] The first bar statistics range is between [1,2) (left closed, right open), and the second bar Between [2,3).
(3) Range, optional, refers to the upper and lower limits of the probability distribution range (corresponding to the minimum and maximum values ​​of the x-axis), if not provided, the default value is (x.min(), x.max()) .
(4) Density, if the value is set to True, the first element of the returned tuple will be normalized to form a count of probability density, that is, the area (or integral) under the histogram will add up to 1. Note that the normed and density parameters can only be used at the same time.
(5) weights, assign weights to all values ​​of x. When normed or density is set to True, this parameter is automatically normalized.
(6) When cumulative, True, the number of samples increases from small to large and accumulates the number in the statistics bar (the rightmost bar will be the highest); when False, the cumulative statistics from large to small (the rightmost bar will be the smallest).
(7) bottom, specify the baseline position of each bar base on the x-axis.
(8) histtype, specify the type of histogram, optional values ​​include'bar','barstacked','step', and'stepfilled'.
(9) align, specify the position of the bar base relative to the baseline on the x-axis, optional values ​​include'left','mid','right', and the default value is'mid'.
(10) Orientation, set the horizontal or vertical display mode of the bar graph, optional values ​​include'horizontal','vertical', and the default value is'vertical'.
(11) rwidth, specify the width of the bar graph, the default value is None, the width is automatically calculated.
(12) log, if the value is "True", the histogram axis will be set to logarithmic scale.
(13) color, set the color of the bar graph. Equivalent to facecolor="blue".
(14) label, set the string information of the legend.
(15) stacked, set to True, then multiple bars are stacked together.
(16) normed, not recommended, please use density keyword parameter instead.

import matplotlib.pyplot as plt
import numpy as np
plt.rc('font',family='simhei',size=15)
plt.rc('axes',unicode_minus=False) #该参数解决负号显示问题
d1 = np.random.randn(10000)
plt.hist(d1,bins=40,facecolor='blue',edgecolor="black",alpha=0.9)  #设置40个条形数量的直方图
plt.xlabel('概率分布区间')
plt.ylabel('频数/频率')
plt.title('频数/频率分布直方图')
plt.show()

Insert picture description here

Guess you like

Origin blog.csdn.net/changshupx/article/details/108636797