Machine Learning - Using the Matplotlib Gallery

Draw a simple line chart plt.plot

import matplotlib.pyplot as plt

#设置数值点
x= [1, 2, 3, 4, 5]
y=[1,4,9,16,25]

#画图
plt.plot(x,y)


# 用黑体显示中文
plt.rcParams['font.sans-serif'] = ['SimHei'] 

#标签
plt.title("折线图", fontsize=24)
plt.xlabel("X轴", fontsize=14) 
plt.ylabel("Y轴", fontsize=14) # 设置刻度标记的大小 

# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)
plt.show()

Draw a simple scatter plot plt.scatter

import matplotlib.pyplot as plt


x= [1, 2, 3, 4, 5]
y= [1, 4, 9, 16, 25]

#输入x,y数据,并s设置点的粗细
plt.scatter(x,y,s=100)

 Calculate data automatically

import matplotlib.pyplot as plt

x = list(range(1, 1001))
y= [x**2 for x in x_values]
plt.scatter(x, y, s=40)

# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])
plt.show()

 Remove outlines of data points

#要删除数据点的轮廓,可在调用scatter() 时传递实参edgecolor='none'
plt.scatter(x, y, edgecolor='none', s=40)

custom color

#要修改数据点的颜色,可向scatter() 传递参数c
plt.scatter(x, y, c='red', edgecolor='none', s=40)


#使用RGB颜色模式自定义颜色,它们分别表示红色、绿色和蓝色分量
plt.scatter(x, y, c=(0, 0, 0.8), edgecolor='none', s=40)
#值越接近0,指定的颜色越深,值越接近1,指定的颜色越浅。

Use colormaps

Set the parameter c to a list of y values, and use the parameter cmap to tell pyplot which colormap to use. These codes display points with small y values ​​in light blue and points with large y values ​​in dark blue

x = list(range(1001))
y = [x**2 for x in x]
plt.scatter(x, y, c=y, cmap=plt.cm.Blues,edgecolor='none', s=40)

 Autosave charts

Replace the call to plt.show() with a call to plt.savefig()

#将对plt.show() 的调用替换为对plt.savefig() 的调用
plt.savefig('plot.png', bbox_inches='tight')

The first argument specifies what filename to save the chart under. This file will be stored in the directory where .py is located;

The second argument specifies that excess white space in the chart is cropped. If you want to keep the extra white space around the chart.

random walk

from random import choice
class RandomWalk():
    """ 一个生成随机漫步数据的类 """
    def __init__(self, num_points=5000):
        """ 初始化随机漫步的属性 """
        self.num_points = num_points
        # 所有随机漫步都始于 (0, 0)
        self.x_values = [0]
        self.y_values = [0]
        
    """选择方向"""    
    def fill_walk(self):
        """ 计算随机漫步包含的所有点 """
        
        # 不断漫步,直到列表达到指定的长度
        while len(self.x_values) < self.num_points:
            # 决定前进方向以及沿这个方向前进的距离
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            # 拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue
            # 计算下一个点的 x 和 y 值
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)

Use choice([1, -1]) to choose a value for x_direction, the result is either 1 for going right or -1 for going left

choice([0, 1, 2, 3, 4]) randomly selects an integer between 0 and 4, telling Python how far to go in the specified direction (x_distance)

If x_step is positive, it will move right, negative will move left, and zero will move vertically; if y_step is positive, it means move up, negative means move down, and zero means move horizontally . If both x_step and y_step are zero, it means standing still, we reject this case and proceed to the next loop

To get the x value of the next point in the walk, we add x_step to the last value in x_values

After getting the x and y values ​​of the next point, we append them to the end of the lists x_values ​​and y_values ​​respectively.

 color the point

Add parameters: c=point_numbers, cmap=plt.cm.Set3

 Redraw start and end points

# 突出起点和终点
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
s=100)

hide the axes

# 隐藏坐标轴 
plt.axes().get_xaxis().set_visible(False) 
plt.axes().get_yaxis().set_visible(False)

add points

#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk(50000)
rw.fill_walk()

Resize to fit screen

# 设置绘图窗口的尺寸 
plt.figure(dpi=128,figsize=(10, 6))

import matplotlib.pyplot as plt
while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()

    # 设置绘图窗口的尺寸 
    plt.figure(dpi=128,figsize=(10, 6))
    
    # 绘制点并将图形显示出来 
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Set3,
    edgecolor='none', s=1)
   
    # 隐藏坐标轴 
    plt.axes().get_xaxis().set_visible(False) 
    plt.axes().get_yaxis().set_visible(False)

    
    # 突出起点和终点
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',s=100)
    plt.show()
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break

Using Pygal to simulate rolling dice

from random import randint
import pygal

class Die():
    """表示一个骰子的类"""
    def __init__(self, num_sides=6):
        """骰子默认为6面"""
        self.num_sides = num_sides
    def roll(self):
        """"返回一个位于1和骰子面数之间的随机值"""
        return randint(1, self.num_sides)

# 创建一个D6
die = Die()


# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1000):
    result = die.roll()
    results.append(result)
# 分析结果
frequencies = []
for value in range(1, die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)
print(frequencies)


# 对结果进行可视化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')

Guess you like

Origin blog.csdn.net/qq_21402983/article/details/123938462