matplotlib - проблема несоответствия формы при попытке добавить больше столбцов

Я новичок в matplotlib и python-диаграммах вообще, поэтому простите меня заранее, если у меня неправильно установлена ​​терминология.

Я пытаюсь создать диаграмму, это комбинация разброса + столбчатых столбцов .

Дело в том, что только количество столбцов совпадает с количеством строк, поскольку я предполагаю, что либо numpy, либо другие библиотеки генерируют формы таким образом (что и упоминается в этой ошибке), но я не могу понять, как добавить больше столбцов и по-прежнему оставаться с таким же количеством строк.

Результат, который я ожидаю, заключается в добавлении, скажем, дополнительных столбцов X в моей текущей 5 * 5 таблице + верхний график.

ниже, любая помощь будет оценена, ошибка будет воспроизведена, когда дополнительные элементы будут переданы в данные [] и data2 []

#!/usr/bin/env python2.7

import os
import sys
import numpy as np
import matplotlib.pyplot as plt

lst_keys_ordered = []
dict_quotes = {}

def main():

    rows = ['bid 5','bid 4','bid 3','bid 2','bid 1','ask 1','ask 2','ask 3','ask 4','ask 5']
    colors = ['red','crimson','indianred','lightcoral','lightsalmon','greenyellow','lawngreen','limegreen','green','darkgreen']
    value_increment = 100
    size_ratio = 50

    """ this config works """
    price = [55,55.5,55.2,55.9,60.3]
    price2 = [55.5,56,55.7,56.5,60.8]
    data = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100]]
    data2 = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100]]
    columns = ('09:30:01', '09:30:02', '09:30:03', '09:30:04', '09:30:05')

    """ below  generates errors - 6 columns data with 5 elements in data list items """
    """ 
    price = [55,55.5,55.2,55.9,60.3,60.3]
    price2 = [55.5,56,55.7,56.5,60.8,60.3]
    data = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100],[80,120,40,60,100]]
    data2 = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100],[80,120,40,60,100]]
    columns = ('09:30:01', '09:30:02', '09:30:03', '09:30:04', '09:30:05', '09:30:06')
    """ 
    for i,row in enumerate(data):
        for j,item in enumerate(row):
            data[i][j] = float(data[i][j])/size_ratio
    for i,row in enumerate(data2):
        for j,item in enumerate(row):
            data2[i][j] = float(data2[i][j])/size_ratio

    n_rows = len(data)

    index = np.arange(len(columns)) + 0.3
    bar_width = 0.4

    # Initialize the vertical-offset for the stacked bar chart.
    y_offset = np.zeros(len(columns))
    # Plot bars and create text labels for the table
    cell_text = []

    for row in range(n_rows):
        print n_rows , index, data[row], bar_width, colors[row]
        plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row],edgecolor="black")
        y_offset = y_offset + data[row]
        cell_text.append(['{0}'.format(x * size_ratio) for x in y_offset])

    for row in range(n_rows):
        plt.bar(index, data2[row], bar_width, bottom=y_offset, color=colors[row + n_rows],edgecolor="black")
        y_offset = y_offset + data2[row]
        cell_text.append(['{0}'.format(x * size_ratio) for x in y_offset])

    # Reverse colors and text labels to display the last value at the top.
    colors = colors[::-1]
    cell_text.reverse()

    cell_text.insert(0,price)
    print("cell_text: {0}".format(cell_text))
    rows.insert(0,"price $")
    print("rows: {0}".format(rows))
    colors.insert(0,"gray")
    # Add a table at the bottom of the axes
    the_table = plt.table(cellText=cell_text,rowLabels=rows,rowColours=colors,colLabels=columns,loc='bottom')

    # Adjust layout to make room for the table:
    plt.subplots_adjust(left=0.2, bottom=0.31)

    plt.ylabel("Level 1 Price {0}$".format(value_increment))
    plt.xticks([])
    plt.title('Integrated Quotes')

    for row in range(n_rows):
        plt.scatter(index[row], price[row] - 1,color="red",s=5)
        plt.annotate(price[row], xy=(index[row], price[row]), xytext=(index[row], price[row] - 1),fontsize=6)
        plt.scatter(index[row], price2[row] + 1,color="green",s=5)
        plt.annotate(price2[row], xy=(index[row], price2[row]), xytext=(index[row], price2[row] + 1),fontsize=6)

    wm = plt.get_current_fig_manager()
    wm.window.state('zoomed')
    plt.show()

if __name__ == "__main__":
    main()  

-1
задан 13 August 2018 в 16:00

0 ответов

Другие вопросы по тегам:

Похожие вопросы: