Instagram
youtube
Facebook
Twitter

Customize Legend Position and Font

Description:
This code plots two lines and customizes the legend’s position, font size, and adds a title to the legend box.

 

Explanation:

  • The legend() function shows which line represents which data.

  • loc='upper left': Moves the legend to the top-left corner of the plot.

  • fontsize='large': Makes the legend text easier to read.

  • title='Products': Adds a header/title to the legend box.

  • These options help make your chart clearer and more professional, especially when multiple lines are present.


Program:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 40]
y2 = [5, 15, 20, 25, 35]

# Plotting the lines
plt.plot(x, y1, label='Product A')
plt.plot(x, y2, label='Product B')

# Customize legend
plt.legend(loc='upper left', fontsize='large', title='Products')

# Titles and labels
plt.title('Sales Comparison')
plt.xlabel('Time')
plt.ylabel('Sales')

# Show the plot
plt.show()


Output: