pandas .hist() legend in python

To add a legend to a histogram created using pandas' .hist() method, you need to create a matplotlib Axes object and set the legend to it. Here's an example:

main.py
import pandas as pd
import matplotlib.pyplot as plt

data = {'values': [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]}
df = pd.DataFrame(data)

ax = df.plot.hist(alpha=0.7)
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.legend(['Counts'])
plt.show()
240 chars
12 lines

In this example, we create a pandas DataFrame with values and then create a histogram using the DataFrame's .hist() method. We set the opacity of the bars using the 'alpha' parameter. We then create a new Axes object 'ax' by calling the .plot.hist() method on the DataFrame and set the legend text to 'Counts' using the .legend() method. Finally, we show the plot using matplotlib's .show() method.

Note that the legend text is passed as a list to .legend(), so if you want to add multiple labels, you can pass a list of labels to it.

gistlibby LogSnag