记录研究生封校生活的学习day9(第一篇)pandas实战(九)

57 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

总计:今天是十月更文计划第九天,第十九篇

今天继续昨天的实战:

绘制正弦曲线,使图形能够响应鼠标事件,当鼠标进入图形区域时设置背景色为黄色,鼠标离开图形区域时背景色恢复为白色,并且当鼠标接近曲线时自动显示当前位置。

编写的代码如下:

import numpy as np
import matplotlib.pyplot as plt

def onMotion(event):
    # 获取鼠标位置和标注可见性
    x = event.xdata
    y = event.ydata
    visible = annot.get_visible()
    if event.inaxes == ax:
        # 测试鼠标事件是否发生在曲线上
        contain, _ = sinCurve.contains(event)
        if contain:
            # 设置标注的终点和文本位置,设置标注可见
            annot.xy = (x, y)
            annot.set_text(str(y))   # 设置标注文本
            annot.set_visible(True)  # 设置标注可见
        else:
            # 鼠标不在曲线附近,设置标注为不可见
            if visible:
                annot.set_visible(False)
        event.canvas.draw_idle()
        
def onEnter(event):
    # 鼠标进入时修改轴的颜色
    event.inaxes.patch.set_facecolor('yellow')
    event.canvas.draw_idle()

def onLeave(event):
    # 鼠标离开时恢复轴的颜色
    event.inaxes.patch.set_facecolor('white')
    event.canvas.draw_idle()
    
fig = plt.figure()
ax = fig.gca()
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
sinCurve, = plt.plot(x, y,      # 绘图数据
                     picker=2)  # 鼠标距离曲线2个像素可识别
# 创建标注对象
annot = ax.annotate("",
                    xy=(0,0),                     # 箭头位置
                    xytext=(-50,50),             # 文本相对位置
                    # 相对于xy的偏移量单位
                    textcoords="offset pixels",
                    # 圆角,红色背景
                    bbox=dict(boxstyle="round", fc="r", alpha=0.4),
                    # 标注箭头形状
                    arrowprops=dict(arrowstyle="<->"))
annot.set_visible(False)

# 添加事件处理函数
fig.canvas.mpl_connect('motion_notify_event', onMotion)  
fig.canvas.mpl_connect('axes_enter_event', onEnter)
fig.canvas.mpl_connect('axes_leave_event', onLeave)

plt.show()

输出的结果为:

image.png

2.编写程序,生成测试数据,绘制水平柱状图,然后每隔0.5秒更新一次数据并实时根据最新数据绘制水平柱状图

编写的程序如下:

x = np.arange(1, 13)
y = np.random.randint(10, 30, 12)
for i in range(20):
    # 清除当前轴域
    plt.cla()
    # 绘制水平柱状图
    plt.barh(x, y)
    plt.title('20%02d年'%i, fontproperties='simhei',fontsize=20)
    plt.yticks(x, list(map(lambda i: '%d月'%i, x)),
                fontproperties='simhei')
    plt.xticks(list(range(0,100,10)))
    # 暂停0.5秒
    plt.pause(0.5)
    # 更新数据
    y = y+np.random.randint(0, 5, 12)
    
plt.show()

输出的结果为:

image.png

3.编写程序,绘制正弦曲线,并在图形窗口上创建单选钮组件调整曲线的颜色、频率和线型,创建按钮组件实现从固定的几种颜色、频率和线型中随机选择。

编写的代码如下:

from random import choice
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons, Button

# 3中不同频率的信号
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(8*np.pi*t)

# 创建图形
fig, ax = plt.subplots()
l, = ax.plot(t, s0, lw=2, color='red')
plt.subplots_adjust(left=0.3)

# 定义允许的几种频率,并创建单选钮组件
# 其中[0.05, 0.7, 0.15, 0.15]表示组件在窗口上的归一化位置
axcolor = '#886699'
rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz'))
hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2}

def hzfunc(label):
    ydata = hzdict[label]
    l.set_ydata(ydata)
    plt.draw()
radio.on_clicked(hzfunc)

# 定义允许的几种颜色,并创建单选钮组件
rax = plt.axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor)
colors = ('red', 'blue', 'green')
radio2 = RadioButtons(rax, colors)
def colorfunc(label):
    l.set_color(label)
    plt.draw()
radio2.on_clicked(colorfunc)

# 定义允许的几种线型,并创建单选钮组件
rax = plt.axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor)
styles = ('-', '--', '-.', 'steps', ':')
radio3 = RadioButtons(rax, styles)
def stylefunc(label):
    l.set_linestyle(label)
    plt.draw()
radio3.on_clicked(stylefunc)

# 定义按钮单击事件处理函数,并在窗口上创建按钮
def randomFig(event):
    # 随机选择一个频率,同时设置单选钮的选中项
    hz = choice(tuple(hzdict.keys()))
    hzLabels = [label.get_text() for label in radio.labels]
    radio.set_active(hzLabels.index(hz))
    l.set_ydata(hzdict[hz])
    
    # 随机选择一个颜色,同时设置单选钮的选中项
    c = choice(colors)
    radio2.set_active(colors.index(c))
    l.set_color(c)
    
    # 随机选择一个线型,同时设置单选钮的选中项
    style = choice(styles)
    radio3.set_active(styles.index(style))
    l.set_linestyle(style)
    
    # 根据设置的属性绘制图形
    plt.draw()
axRnd = plt.axes([0.5, 0.015, 0.2, 0.045])
buttonRnd = Button(axRnd, 'Random Figure', color='0.6', hovercolor='r')
buttonRnd.on_clicked(randomFig)

# 显示图形
plt.show()

输出的结果为:

image.png