matplotlib-尝试添加更多列时形状不匹配的问题

时间:2018-08-13 13:00:21

标签: python matplotlib charts shapes

我一般是matplotlib和python图表的新手,所以如果我弄错了术语,请事先谅解。

我正在尝试生成图表,它是散点图+堆积的柱状图的组合。

问题是,当列数与行数相同时,这是唯一的问题,因为我假设numpy或其他库都以这种方式生成形状(这是错误所提到的),但我无法弄清楚如何添加更多列,并且仍然保持相同的行数。

我期望的结果是在表格+上方图表的当前5 * 5中添加其他X列。

下面的代码,将不胜感激,当data []和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()  

enter image description here

1 个答案:

答案 0 :(得分:2)

如果目标是向数据添加另一列,则行数应保持不变。在下面的代码中,我在数据中又增加了一列(由50到150组成)。

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,60.3]
    price2 = [55.5,56,55.7,56.5,60.8,61,9]
    data = [[100,200,100,200,100,50],[20,200,50,100,50,60],[100,100,50,50,300,70],[400,50,100,50,50,80],[80,120,40,60,100,90]]
    data2 = [[100,200,100,200,100,110],[20,200,50,100,50,120],[100,100,50,50,300,130],[400,50,100,50,50,140],[80,120,40,60,100,150]]
    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 col in range(len(price)):
        plt.scatter(index[col], price[col] - 1,color="red",s=5)
        plt.annotate(price[col], xy=(index[col], price[col]), xytext=(index[col], price[col] - 1),fontsize=6)
        plt.scatter(index[col], price2[col] + 1,color="green",s=5)
        plt.annotate(price2[col], xy=(index[col], price2[col]), xytext=(index[col], price2[col] + 1),fontsize=6)

    plt.show()

if __name__ == "__main__":
    main() 

this