代码之家  ›  专栏  ›  技术社区  ›  TheCrystalShip

Matplotlib轴图例在条形图中仅显示一个标签

  •  1
  • TheCrystalShip  · 技术社区  · 6 年前

    我有15个barh子图,看起来像这样:

    enter image description here

    我似乎无法使图例正常工作,因此我将在图表和图例中看到[2,3,4]作为单独的标签。

    我在处理子图时遇到了麻烦。我的代码:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    def plot_bars_by_data(data, title):
        fig, axs = plt.subplots(8,2, figsize=(20,40))
        fig.suptitle(title, fontsize=20)
        fig.subplots_adjust(top=0.95)
        plt.rcParams.update({'font.size': 13})
        axs[7,1].remove()
    
        column_index = 0
        for ax_line in axs:
            for ax in ax_line:
                if column_index < len(data.columns): 
                    column_name = data.columns[column_index]
                    current_column_values = data[column_name].value_counts().sort_index()
                    ax.barh([str(i) for i in current_column_values.index], current_column_values.values)
                    ax.legend([str(i) for i in current_column_values.index])
                    ax.set_title(column_name)
                    column_index +=1
    
        plt.show()
    
    # random data
    df_test = pd.DataFrame([np.random.randint(2,5,size=15) for i in range(15)], columns=list('abcdefghijlmnop'))
    plot_bars_by_data(df_test, "testing")
    

    我刚得到一个8x2的条,看起来像上面的图表。我怎样才能解决这个问题? 我正在使用python3.6和jupyterpython笔记本。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Sheldore    6 年前

    在代码中使用以下行。我不能把整个输出放在这里,因为它是一个大的数字,有很多子图,因此显示了一个特定的子图。结果是,首先必须为子图创建一个句柄,然后传递图例值和句柄以生成所需的图例。

    colors = ['r', 'g', 'b']
    axx = ax.barh([str(i) for i in current_column_values.index], current_column_values.values, color=colors)
    ax.legend(axx, [str(i) for i in current_column_values.index])
    

    enter image description here