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

是的

我一般是 matplotlib 和 python 图表的新手,所以如果我的术语有误,请提前原谅我。

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

问题是只有当列数与行数相同时才可以,因为我假设 numpy 或其他库以这种方式生成形状(这是错误提到的),但我不知道如何添加更多的列,并且仍然保持相同的行数。

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

下面的代码,任何帮助将不胜感激,当数据 [] 和 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()  

在此处输入图片说明

存在的重要性欧内斯特

如果目的是向数据添加另一列,则行数应保持不变。在下面的代码中,我向数据添加了另一列(由数字 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() 

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章