如何使用y轴可以正确看到的python在一帧中绘制多个图?

时间:2018-10-17 23:03:18

标签: python-3.x matplotlib

我已经使用matpoltlib在一帧中编写了多个图的python代码。当我看到自己的图像时,Y轴未正确显示标题(实际上是重叠或被数字切割等),X轴应有一个标题,因为X轴对于所有四个(温度,电位,总和)都相同,压力)。我已经上传了图片。如果看不到它。请让我知道。

initial.txt文件如下所示:

   0      1865.74   -388642.31   -362596.65   -57421.263 
 100    100.39272   -388659.69   -387258.21   -68103.868 
 200    100.34027   -388677.95    -387277.2   -68090.633 
 300    100.25494   -388696.92   -387297.36    -68081.08 
 400    100.28753   -388716.37   -387316.36   -68072.858 
 500    100.27897   -388736.41   -387336.52    -68067.56 
 600    100.27288   -388757.61    -387357.8   -68056.853
 .
 . 

输入脚本:

import numpy as np
import matplotlib.pyplot as plt

x, y1, y2, y3, y4 = [], [],[], [], []

with open("initial.txt") as f:
    for line in f:
        cols = line.split()

        if len(cols) == 5:
            x.append(float(cols[0]))
            y1.append(float(cols[1]))
            y2.append(float(cols[2]))
            y3.append(float(cols[3]))
            y4.append(float(cols[4]))


plt.subplot(411)
plt.plot(x, y1, '-')
plt.title('initial_output')
plt.ylabel('temperature')

plt.subplot(412)
plt.plot(x, y2, '-')
plt.ylabel('potential')

plt.subplot(413)
plt.plot(x, y3, '-')
plt.ylabel('temperature')

plt.subplot(414)
plt.plot(x, y4, '-')
plt.xlabel('steps')
plt.ylabel('pressure')

plt.savefig("a.jpeg", dpi=100)

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为最终您只需要Write-Output。它重新排列了多图图形。
请注意可选的-InputObject-kwarg,它允许在重新排列子图中定义一个区域,例如为了与全局人物标题保持距离(另请参见下面的示例)。

但是,如果仍然使用plt.tight_layout(),则不需要手动导入文本文件。使用例如rect

numpy

然后,在一个雕像中创建多个图形的便捷方法是genfromtxt。例如。它有一个简单的关键字,可以为所有子图共享一个x轴:

data = np.genfromtxt('initial.txt', names='x', 'temp_1','potential','temp_2', 'pressure'])

array([(  0., 1865.74   , -388642.31, -362596.65, -57421.263),
       (100.,  100.39272, -388659.69, -387258.21, -68103.868),
       (200.,  100.34027, -388677.95, -387277.2 , -68090.633),
       (300.,  100.25494, -388696.92, -387297.36, -68081.08 ),
       (400.,  100.28753, -388716.37, -387316.36, -68072.858),
       (500.,  100.27897, -388736.41, -387336.52, -68067.56 ),
       (600.,  100.27288, -388757.61, -387357.8 , -68056.853)],
      dtype=[('x', '<f8'), ('temp_1', '<f8'), ('potential', '<f8'), ('temp_2', '<f8'), ('pressure', '<f8')])

然后仅遍历您的数据和轴并完成操作:

plt.subplots

结果:

enter image description here

这就是全部内容:如果您想要真正方便的数据导入,分析和绘图,请查看fig, axs = plt.subplots(4, 1, sharex=True) fig.suptitle('initial_output') https://pandas.pydata.org/