【发布时间】:2021-02-10 12:13:41
【问题描述】:
我正在尝试为每个聚合物长度绘制不同的直方图,每个都在一个单独的窗口中。
import matplotlib.pyplot as plt
for polymer_length in polymer_lengths:
with open('radii_{0}d_N{1}_l{2}.txt'.format(int(dim), polymer_length, int(monomer_length))) as radii_file:
radii_raw = radii_file.readlines()
nice_radii = []
for ele in radii_raw[1:]:
nice_radii.append(float(ele))
plt.style.use('fivethirtyeight')
plt.hist(nice_radii, bins=25, rwidth=0.95)
plt.title('Histogram for Polymer length {} with monomer length {}, in {}D'.format(polymer_length, int(monomer_length), int(dim)))
plt.xlabel('Radius')
plt.ylabel('Number of Radii')
plt.tight_layout()
plt.show()
注意事项:
- 这只是程序的一部分。我有不同的
.txt文件,每个文件都包含程序计算过的每个半径。每个文件都需要通过聚合物参数进行区分,因此需要使用单独的直方图。
编辑:
感谢 tmdavison,我已将代码更改为
plt.title('Histogram for Polymer length {} with monomer length {}, in {}D'.format(polymer_length, int(monomer_length), int(dim)))
plt.xlabel('Radius')
plt.ylabel('Number of Radii')
plt.tight_layout()
plt.figure()
现在我确实得到了单独的直方图,但它绘制了一个额外的空图。
【问题讨论】:
-
在绘制第二个和第三个直方图之前使用
plt.figure()创建一个新图形 -
或者,更好的是,使用 matplotlib 面向对象的方法来更轻松地跟踪每个图形上绘制的内容:matplotlib.org/3.3.3/tutorials/introductory/…
-
谢谢,我已经添加了命令并删除了
plt.show(),它运行良好但现在它绘制了一个额外的空图。 -
plt.figure应该在plt.hist之前 -
在绘制每个图之前使用 plt.figure()。不是在之后
标签: python matplotlib histogram