在matplotlib中绘制数据文件中的数据

时间:2014-05-20 18:50:28

标签: python matplotlib plot

我有16行3列的测试数据文件,如下所示:

4.0 4.0 0.992561656631 
7.33333333333 4.0 0.983625465545 
4.0 7.33333333333 0.983625465545 
7.33333333333 7.33333333333 0.973260418741 
10.6666666667 4.0 0.973385993787 
4.0 10.6666666667 0.973385993787 
10.6666666667 7.33333333333 0.96232158762 
7.33333333333 10.6666666667 0.96232158762 
10.6666666667 10.6666666667 0.947002325682 
14.0 4.0 0.963985902172 
4.0 14.0 0.963985902172 
14.0 7.33333333333 0.948250293872 
7.33333333333 14.0 0.948250293872 
14.0 10.6666666667 0.933855073978 
10.6666666667 14.0 0.933855073978 
14.0 14.0 0.91658870141

实际上,前两列显示坐标,第三列显示该坐标中函数的值。如果您愿意,您可以将此表视为4x4矩阵。

现在,我想将此数据文件绘制为彩色2D绘图,前两列显示坐标,第三列显示框的颜色。

以下是我的代码的一部分,应该负责绘图:

    x3,y3,z3 = np.loadtxt("./data/FDFD_Real_Effectualness_m1m2_mo_%s_%s.dat" % (waveform2, waveform1)).T

    nrows, ncols = final_step_j-1, final_step_k-1
    grid3 = z3.reshape((nrows, ncols))

fig3 = plt.gcf()
            plt.xlabel('$m_1$')
            plt.ylabel('$m_2$')
            plt.imshow(grid3, extent=(x3.min(), x3.max(), y3.min(), y3.max()), origin='lower', aspect='auto', interpolation='nearest', cmap=cm.gist_rainbow)
            fig3.suptitle('Effectualness of %s and %s' % (waveform1, waveform2))
            plt.colorbar()
            plt.draw()
            fig3.savefig('./plots/FDFD_Real_Effectualness_m1m2_mo_%s_%s.pdf' %(waveform1, waveform2), dpi=100)
            plt.close()

结果看起来不像预期的那样(附图)。特别地,从数据中可以清楚地看出结果应该是对角对称的。任何建议都是受欢迎的。 enter image description here

1 个答案:

答案 0 :(得分:2)

您需要在将数据重新整形为网格之前对其进行排序:

import pylab as pl
import io
import numpy as np

txt = """4.0 4.0 0.992561656631
7.33333333333 4.0 0.983625465545
4.0 7.33333333333 0.983625465545
7.33333333333 7.33333333333 0.973260418741
10.6666666667 4.0 0.973385993787
4.0 10.6666666667 0.973385993787
10.6666666667 7.33333333333 0.96232158762
7.33333333333 10.6666666667 0.96232158762
10.6666666667 10.6666666667 0.947002325682
14.0 4.0 0.963985902172
4.0 14.0 0.963985902172
14.0 7.33333333333 0.948250293872
7.33333333333 14.0 0.948250293872
14.0 10.6666666667 0.933855073978
10.6666666667 14.0 0.933855073978
14.0 14.0 0.91658870141"""

data = np.loadtxt(io.BytesIO(txt), delimiter=" ")
idx = np.lexsort((data[:, 0], data[:, 1]))
data = data[idx]
pl.imshow(data[:, 2].reshape(4, 4), origin='lower', interpolation='nearest')

这是输出:

enter image description here