【发布时间】:2021-03-06 14:57:20
【问题描述】:
大家晚上好,
我试图编写一个程序,使用matplotlib radio buttons 在同一轴上的两个等高线图之间交替。
当每个等高线图都给定了自己的绘图框时,这两个等高线图都成功绘图。等高线图(由字典density_A 和density_Z 表示是彼此的镜像。见下图
更新
是的,所以当我点击radio 按钮时,我实际上能够得到 Density Z 图替换 Density A 图。这是对通常替代密度 A 的灰色斑点的改进。请参见下图。
未解决的问题:
- 点击
radio button Density A时,绘图不会恢复为原始密度 A 绘图。
我在def change_plot 函数中尝试了一系列if/else statements。
欢迎提出任何建议。
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
from matplotlib.widgets import RadioButtons
# Junk data for the purpose of my question
x = [1, 1, 1, 2, 2, 2, 3, 3, 3]
y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
density_A = [1, 1, 1, 1, 0, 1, 1, 1, 1]
density_Z = [0, 0, 0, 0, 1, 0, 0, 0, 0]
fig, (ax1, ax2) = plt.subplots(1, 2)
"""
# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.
"""
ngridx = 1000
ngridy = 2000
# Create grid values first.
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)
# Linearly interpolate the data (x, y) on a grid defined by (xi, yi).
triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, density_A)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)
"""
# ----------
# Tricontour
# ----------
Contour plot is generated here.
"""
ax1.tricontour(x, y, density_A, levels=100, linewidths=0.25, colors='k')
cntr2 = ax1.tricontourf(x, y, density_A, levels=100, cmap="terrain") # Colour Bar has colour scheme RdBu_r
ax2.tricontour(x, y, density_Z, levels=100, linewidths=0.25, colors='k')
cntr3 = ax2.tricontourf(x, y, density_Z, levels=100, cmap="terrain") # Colour Bar has colour scheme RdBu_r
"""
# ----------
# Plot Setup
# ----------
Defining the layout for ax1, ax2 and radio box
"""
fig.colorbar(cntr2, ax=ax1)
ax1.set_title('Density A')
ax1.plot(x, y, 'ko', ms=2.5)
ax1.set(xlim=1, ylim=1) # Sets up the grid
fig.colorbar(cntr3, ax=ax2)
ax2.set_title('Density Z')
ax2.plot(x, y, 'ko', ms=2.5)
ax2.set(xlim=1, ylim=1) # Sets up the grid
# Radio box formmating
axcolor = 'lightgoldenrodyellow'
rax = plt.axes([.05, 0.7, 0.15, 0.15])
radio = RadioButtons(rax, ('Density A', 'Density Z'))
def change_plot(label):
density_options = {'Density A': ax1.tricontourf(x, y, density_A, levels=100, cmap="terrain") and ax1.set_title('Density A') and ax1.plot(x, y, 'ko', ms=2.5),
'Density Z': ax1.tricontourf(x, y, density_Z, levels=100, cmap="terrain") and ax1.set_title('Density Z') and ax1.plot(x, y, 'ko', ms=2.5)}
plt.draw()
radio.on_clicked(change_plot) #change plot to the corresponding radio button
plt.show() #display the plot
【问题讨论】:
标签: python matplotlib plot contour radio