MatPlotLib将图形打印在彼此相邻的同一行上

时间:2017-11-09 22:18:04

标签: python matplotlib

所以我正在创建一个读取多个二维列表的程序,并将它们绘制为步骤图函数。我想像这样并排打印出每组图表(我将图表设为不同的颜色,只是为了区分两者):

Desired Output

但是我的代码现在使这两个集合相互重叠,如下所示:

Actual Output

我相信它可能与plotPoints中的“t”变量有关,但我不确定我需要做什么。任何帮助将不胜感激。

# supress warning message
import warnings; warnings.simplefilter("ignore")
# extension libraries
import matplotlib.pyplot as plt
import numpy as np


def plotPoints(bits, color):
    for i in range(len(bits)):
        data = np.repeat(bits[i], 2)
        t = 0.5 * np.arange(len(data))

        plt.step(t, data + i * 3, linewidth=1.5, where='post', color=color)


        # Labels the graphs with binary sequence
        for tbit, bit in enumerate(bits[i]):
            plt.text(tbit + 0.3, 0.1 + i * 3, str(bit), fontsize=6, color=color)


def main():

    plt.ylim([-1, 32])

    set1 = [[0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0]]
    set2 = [[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1]]


    plotPoints(set1, 'g')
    plotPoints(set2, 'b')


    # removes the built in graph axes and prints line every interation
    plt.gca().axis('off')
    plt.ylim([-1, 10])


    plt.show()

main()

1 个答案:

答案 0 :(得分:1)

您可以向t添加一些偏移量。

import matplotlib.pyplot as plt
import numpy as np


def plotPoints(bits, color, offset=0):
    for i in range(len(bits)):
        data = np.repeat(bits[i], 2)
        t = 0.5 * np.arange(len(data)) + offset

        plt.step(t, data + i * 3, linewidth=1.5, where='post', color=color)


        # Labels the graphs with binary sequence
        for tbit, bit in enumerate(bits[i]):
            plt.text(tbit + 0.3 +offset, 0.1 + i * 3, str(bit), fontsize=6, color=color)


def main():

    set1 = [[0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0]]
    set2 = [[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1]]


    plotPoints(set1, 'g')
    plotPoints(set2, 'b', offset=len(set1[0]))


    # removes the built in graph axes and prints line every interation
    plt.gca().axis('off')
    plt.ylim([-1, 10])


    plt.show()

main()

enter image description here