简体   繁体   中英

Matplotlib Axes legend shows only one label in barh

I have 15 barh subplots that looks like this:

在此处输入图片说明

I can't seem to get the legend working, so I'll see [2,3,4] as separate labels in the graph and in the legend.

I'm having trouble with making this work for subgraphs. My code:

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")

I just get a 8x2 bars that looks like the above graph. How can I fix this? I'm using Python 3.6 and Jupyter Python notebook.

Use the following lines in your code. I can't put the whole output here as its a large figure with lots of subplots and hence showing a particular subplot. It turns out that first you have to create a handle for your subplot and then pass the legend values and the handle to produce the desired legends.

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])

Sample Output

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM