Matplotlib 简单绘图

作为线性图的替代,可以通过向plot()函数添加格式字符串来显示离散值。 可以使用以下格式化字符。

字符 描述
‘-’ 实线样式
‘–’ 短横线样式
‘-.’ 点划线样式
‘:’ 虚线样式
‘.’ 点标记
‘,’ 像素标记
‘o’ 圆标记
‘v’ 倒三角标记
‘^’ 正三角标记
‘<’ 左三角标记
‘>’ 右三角标记
‘1’ 下箭头标记
‘2’ 上箭头标记
‘3’ 左箭头标记
‘4’ 右箭头标记
‘s’ 正方形标记
‘p’ 五边形标记
‘*’ 星形标记
‘h’ 六边形标记 1
‘H’ 六边形标记 2
‘+’ 加号标记
‘x’ X 标记
‘D’ 菱形标记
‘d’ 窄菱形标记
' ' 竖直线标记
‘_’ 水平线标记

还定义了以下颜色缩写。

字符 颜色
‘b’ 蓝色
‘g’ 绿色
‘r’ 红色
‘c’ 青色
‘m’ 品红色
‘y’ 黄色
‘k’ 黑色
‘w’ 白色

导入要使用的库:
import numpy as np
from matplotlib import pyplot as plt

一.折线图:

x=np.arange(0,360)
y=np.sin(x*np.pi/180.0) #函数
z=np.cos(x*np.pi/180.0)
plt.plot(x,y,color="blue")#xy轴坐标,以及线的颜色
plt.plot(x,z,color="red")
plt.xlim(0,360) #x轴的取值范围
plt.ylim(-1.2,1.2) #y轴的取值范围
plt.title("SIN & COS function") #名称
plt.show() #显示图形

这里写图片描述

二.柱形图:

x=['a','b','c','d','e']
y=[100,200,300,200,500]
ind=np.arange(len(x)) #表示有几根柱子
plt.bar(ind,y)
plt.xticks(ind,x) #不加此句则柱底为0开始的数字
plt.title('myplt') #不加此句则没有名称
plt.show() #显示图形

这里写图片描述

三.饼状图:

speed_map = {
    'dog': (48, '#7199cf'),
    'cat': (45, '#4fc4aa'),
    'cheetah': (120, '#e1a7a2')
}
name=speed_map.keys() #宠物名称
speeds = [x[0] for x in speed_map.values()]# 奔跑速度
colors = [x[1] for x in speed_map.values()] # 对应颜色
labels = ['{}\n{} km/h'.format(animal, speed) for animal, speed in zip(name, speeds)] #设置标签
#画饼状图,并指定标签和对应颜色
plt.pie(speeds, labels=labels, colors=colors)
plt.show() #显示图形

这里写图片描述

四、绘制动态柱状图,每隔5秒刷新一次

import requests
import re
import time
import matplotlib
from pylab import mpl
from threading import Thread
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

import tkinter as tk


# matplotlib.use('TkAgg')

class Application(tk.Tk):
    '''
    文件夹选择程序
        界面与逻辑分离
    '''

    def __init__(self):
        '''初始化'''
        super().__init__()  # 有点相当于tk.Tk()
        self.isRun=True
        # self.result=self.get_data()
        # self.get_data()

        # self.createWidgets()
        self.drawPic()

    def createWidgets(self):
        '''界面'''
        fig = Figure(figsize=(5, 4), dpi=100)
        self.ax = fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(fig, master=self)
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        footframe = tk.Frame(master=self).pack(side=tk.BOTTOM)

        tk.Button(master=footframe, text='重画', command=self.draw).pack(side=tk.BOTTOM)
        tk.Button(master=footframe, text='退出', command=self._quit).pack(side=tk.BOTTOM)

        self.draw()  # 绘图

    def drawPic(self):
        '''根据恒生指数成分股数据画出条形图,属于动态图'''
        self.fig = Figure(figsize=(12, 6), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        footframe = tk.Frame(master=self).pack(side=tk.BOTTOM)

        #tk.Button(master=footframe, text='重画', command=self.tk_show).pack(side=tk.BOTTOM)
        tk.Button(master=footframe, text='退出', command=self._quit).pack(side=tk.BOTTOM)

        #mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体
        #mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


        #self.tk_show()  # 绘图
        t = Thread(target=self.tk_show, args=(), name='get_date')
        t.setDaemon(True)
        t.start()

        # rdm = random.randint
        # result = get_date()
        # result = [(i[0] + rdm(-10, 10), i[1]) for i in result]  # 模拟数据变化



        # plt.xticks(ind,x)

        # drawPic.patch.set_facecolor("white")  # 设置背景颜色
        # drawPic.title(f'恒生指数成分股({len(x)})')
        # pt.grid(True, linestyle='-.')  #网格, color='r', linewidth='3'

    def tk_show(self):
        ''' 循环绘图 '''
        while self.isRun:
            try:
                result = self.get_data()
                self.wm_title("恒生指数成分股(%s)"%len(result))
            except Exception as exc:
                print(exc)
                time.sleep(10)
                continue
            ax = self.ax
            ax.clear()
            color_type = lambda x: 'green' if x < 0 else 'red'
            x = ['\n'.join(i[1].replace('\'','').replace('A','')) for i in result]
            y = [i[0] for i in result]
            x1 = [i[1][0] for i in result]
            print(result)
            ind = np.arange(len(x))
            ax.bar(ind, y, color=[color_type(i[0]) for i in result])  # color条形颜色

            #ax.set_facecolor('black')
            #ax.set_xticks(x)

            #ax.set_xticklabels(x,colors='red')


            #matplotlib.pyplot.xticks(ind, x, fontsize=10,color='green')  # fontsize=10, color='green' fontsize字体大小,color字体颜色,rotation=270 旋转度数
            ax.grid(axis='y', linestyle='-.')

            # t = Thread(target=self.get_data, args=(), name='get_date')
            # t.setDaemon(True)
            # t.start()

            self.canvas.show()
            time.sleep(5)

    def draw(self):
        '''绘图逻辑'''
        x = np.random.randint(0, 50, size=100)
        y = np.random.randint(0, 50, size=100)

        # self.fig.clf()                  # 方式一:①清除整个Figure区域
        # self.ax = self.fig.add_subplot(111)    # ②重新分配Axes区域
        self.ax.clear()  # 方式二:①清除原来的Axes区域

        self.ax.scatter(x, y, s=3)  # 重新画

        self.canvas.show()

    def _quit(self):
        '''退出'''
        self.isRun=False
        self.quit()  # 停止 mainloop
        self.destroy()  # 销毁所有部件

    def get_data(self, url=None):
        '''获取恒生指数成分股数据,格式为:
        [(34, '腾讯控股'), (27, '香港交易所'), (21, '建设银行'), (18, '中国银行'), (16, '工商银行')...]'''

        # while 1:
        url = url if url else 'https://www.hsi.com.hk/HSI-Net/HSI-Net?cmd=nxgenindex&index=00001&sector=00'
        req = requests.get(url).text
        req = re.sub('\s', '', req)
        # req=re.findall('<constituentscount="51">(.*?)</stock></constituents><isContingency>',req)
        com = re.compile('contribution="([+|-]*\d+)".*?<sname>(.*?)</sname></stock>')
        s = re.findall(com, req)
        # print(s)
        result = [(int(i[0]), i[1]) for i in s if i[0] != '0']
        result.sort()
        result.reverse()
        return result


if __name__ == '__main__':
    # 实例化Application
    app = Application()

    # 主消息循环:
    app.mainloop()

执行效果如下:
恒生指数权重股

猜你喜欢

转载自blog.csdn.net/a649344475/article/details/81157643
今日推荐