add legend to pandas.plot() in python

To add a legend to a pandas.plot() plot in Python, you can use the legend parameter of the plot function. This parameter accepts a boolean value to determine whether to display the legend or not.

Here's an example of how you can add a legend to a pandas.plot() plot:

main.py
import pandas as pd

# Create a DataFrame
data = {'x': [1, 2, 3, 4, 5],
        'y': [2, 4, 6, 8, 10]}
df = pd.DataFrame(data)

# Plot the data using pandas.plot()
df.plot(x='x', y='y')

# Add a legend
plt.legend(['y'])

# Display the plot
plt.show()
251 chars
16 lines

In this example, we first create a DataFrame with two columns x and y. We then call the plot() function on the DataFrame and specify the x and y columns to plot.

After that, we use the plt.legend() function from the matplotlib library to add a legend to the plot. The legend function takes a list of labels for the legend items.

Finally, we use the plt.show() function to display the plot with the legend.

Make sure you have imported matplotlib as import matplotlib.pyplot as plt before running this code.

related categories

gistlibby LogSnag