如何使Matplotlib滑块从一个图表输出,并在另一个图表上添加标记

2024-06-26 07:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个绘图,其中一个有一个滑块,可以为连接到楔块(三角形)的线的移动设置动画。另一个图是简单的x-y图。移动我定义的20度楔形体上的直线角度时,其角度将显示在绘图上。我想在另一个图的楔形角和生成的线角位置绘制一个星形。如何将(x,y)数据传输到其他绘图?我在下面附上了一张图片和代码。对于下面的图,楔形是20度,然后直线是34.9度,我想在左图(x,y)=(20,34.9)处画一个星形或填充圆

import math
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
from matplotlib.widgets import Slider  # import the Slider widget

def update(Beta):
    torad = np.pi/180
    y = findy(x3, Beta)
    betatext.set_text(r'$\beta = %.1f$' % Beta)
    y = [0, y]
    line.set_ydata(y)
    fig.canvas.draw_idle()      

def findy(x3, Beta):
    y = x3*np.tan(Beta * torad)
    return y

# ----------------
#  End of Defs
# ----------------

#General constants
torad = np.pi/180
todeg = 1/torad
beta = 40.
Wedge_Angle = 20.
xmax = 10
ymax = 10
axcolor = 'lightgoldenrodyellow'

# TBM constants
gam = 1.4
Mach = 3
tmax = 50
bmax = 92
Npts = 50

#Slider min max
s_min = 25
s_max = 45
s_init = 2

# Define Triangle points
x1 = 0
y1 = 0
x2 = xmax
y2 = y1
x3 = x2
y3 = x3*np.tan(Wedge_Angle * torad)
points = [[x1,y1],[x2,y2],[x3,y3]]

# Define x, y plot data (arbitrary)
t_tbm = [0, 5, 10,  30, 10, 5]
b_tbm = [0, 30, 40, 50, 60, 70]

# Define figure and rectangles
fig = plt.figure(figsize=(7,3))
rect1 = [0.1, 0.1, 0.4, 0.8]
rect2 = [0.5, 0.1, 0.4, 0.8]

##rect = [left, bottom, width, height].
rect1 = [0.1, 0.2, 0.35, 0.8]
rect2 = [0.5, 0.35, 0.4, 0.6]
rectsl = [0.55, 0.15, 0.3, .03]

#Define Mach Numbers
M_list = [2.0]

# Add axis
ax1 = fig.add_axes(rect1,xlim=(0,tmax),ylim=(0, bmax))
ax2 = fig.add_axes(rect2,xlim=(0,xmax),ylim=(0, ymax))

# (Left Plot) Draw TBM Diagram for a variety of Mach numbers
ax1.plot(t_tbm, b_tbm, label=r"$M_1 = \,{}$".format(Mach if (Mach<50) else "\infty"))

## Axis arguments
ax1.set_xlabel(r"Flow Deflection Angle, $\theta$ ($^\circ$)")
ax1.set_ylabel(r"Shock Wave Angle, $\beta$ ($^\circ$)")
ax1.legend(loc=4,fontsize='x-small')
ax1.grid(True)
ax2.text(4, 0.5, r'$\theta = %d$' % Wedge_Angle)

## Right Plot
# Draw the Triangle
polygon = plt.Polygon(points, facecolor='0.9', edgecolor='0.5')
plt.gca().add_patch(polygon)

# Draw the Line
x2 = x3
y2 = findy(x3, beta)
y = x3*np.tan(beta * torad)

line = plt.Line2D((x1,x2),(y1,y2))  
plt.gca().add_line(line)
betatext = ax2.text(1, 9.0, r'$\beta = %.1f$' % beta)

#Plot slider
slider_ax = plt.axes(rectsl, facecolor=axcolor) 

# Now define slider info
svalue = Slider(slider_ax, 'M', s_min, s_max, valinit=s_init, valfmt="%1.2f")
svalue.on_changed(update)

plt.show()

enter image description here

提前谢谢你的帮助


Tags: importnplinefigpltbetaslidermach