python-3.x - 如何停止在此单元格中打印图表,但下一个单元格的代码非常短
问题描述
这些代码生成图表
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
Jupyter notebook 自动打印图表,即使我没有调用plt.show()
. 我不想在与代码相同的单元格中显示图表,而是通过运行非常短的代码(例如plt.show()
. 为了使单元格尽可能简洁。
解决方案
只需将所有与绘图相关的语句包含在一个名为 plot_and_show() 的函数中。然后,您可以在准备好时调用该函数。
import matplotlib.pyplot as plt
import numpy as np
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
def plot_and_show():
p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plot_and_show()
推荐阅读
- swiftui - SwiftUI @ObservedObect 没有更新
- flutter - 打开应用后 Flutter 底部导航栏默认页面
- mysql - Azure Database for MySQL 的客户端证书和密钥
- google-sheets - 如何在 Google Sheet 中将范围转换为文本/字符串
- java - Android 在屏幕上动态更改距离 - 现在仅在方向更改时更改
- ansible - 使用 when 模块执行 ansible playbook
- webots - 在 Webots 中的实体节点上应用用户定义的力
- laravel - Laravel,为什么找不到我的定义路由错误 404?
- applescript - Applescript - 无法访问对象内的变量,具体取决于应用程序
- java - PrintClassHistogramAfterFullGC/PrintClassHistogramBeforeFullGC后如何分离GC日志和Histo?