Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib histogram with multiple legend entries

Tags:

I have this code that produces a histogram, identifying three types of fields; "Low", "medium" , and "high":

import pylab as plt import pandas as pd   df = pd.read_csv('April2017NEW.csv', index_col =1) df1 = df.loc['Output Energy, (Wh/h)']  # choose index value and Average df1['Average'] = df1.mean(axis=1)  N, bins, patches = plt.hist(df1['Average'], 30)  cmap = plt.get_cmap('jet') low = cmap(0.5) medium =cmap(0.25) high = cmap(0.8)   for i in range(0,4):     patches[i].set_facecolor(low) for i in range(4,11):     patches[i].set_facecolor(medium) for i in range(11,30):     patches[i].set_facecolor(high)  plt.xlabel("Watt Hours", fontsize=16)   plt.ylabel("Households", fontsize=16) plt.xticks(fontsize=14)   plt.yticks(fontsize=14) ax = plt.subplot(111)   ax.spines["top"].set_visible(False)   ax.spines["right"].set_visible(False)  plt.show() 

that produces this:

enter image description here

How do I get a legend in there for the three different colors?

like image 247
warrenfitzhenry Avatar asked May 09 '17 14:05

warrenfitzhenry


People also ask

How do you plot a histogram in Matplotlib?

Plot a histogram using hist () method. Make a list of colors to color the face of each patch. Iterate the patches and set face color of each patch. Create a list of handles to place the legend. Use legend () method for multiple legend entries.

How to plot a histogram with multiple legend entries in Python?

To plot a histogram with multiple legend entries, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Plot a histogram using hist () method. Make a list of colors to color the face of each patch. Iterate the patches and set face color of each patch.

How to draw multiple legends on the same axis in Matplotlib?

matplotlib Multiple Legends on the Same Axes. Example. If you call plt.legend() or ax.legend() more than once, the first legend is removed and a new one is drawn. According the official documentation: Fear not, though: It is still quite simple to add a second legend (or third, or fourth...) to an axes.

How to create legend for scatter plot in Matplotlib?

1 Matplotlib scatter plot different colors in legend and plot 3 Create legend for scatter plot using the label of the samples in matplotlib 7 matplotlib: match legend text color with symbol in scatter plot


1 Answers

You would need to create the legend yourself. To this end, create some rectangles, which are not shown in the figure (so called proxy artists).

#create legend handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]] labels= ["low","medium", "high"] plt.legend(handles, labels) 

Complete example:

import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle  data = np.random.rayleigh(size=1000)*35  N, bins, patches = plt.hist(data, 30, ec="k")  cmap = plt.get_cmap('jet') low = cmap(0.5) medium =cmap(0.25) high = cmap(0.8)   for i in range(0,4):     patches[i].set_facecolor(low) for i in range(4,11):     patches[i].set_facecolor(medium) for i in range(11,30):     patches[i].set_facecolor(high)  #create legend handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]] labels= ["low","medium", "high"] plt.legend(handles, labels)  plt.xlabel("Watt Hours", fontsize=16)   plt.ylabel("Households", fontsize=16) plt.xticks(fontsize=14)   plt.yticks(fontsize=14)  plt.gca().spines["top"].set_visible(False)   plt.gca().spines["right"].set_visible(False)  plt.show() 

enter image description here

like image 115
ImportanceOfBeingErnest Avatar answered Oct 13 '22 00:10

ImportanceOfBeingErnest