1. Matplotlib intro
1.1. Installation
Use pip install matplotlib
from the command line in the terminal.
1.2. Importing Pyplot
import matplotlib.pyplot as plt
1.2.1. Some code comments
1.3. Figure
plt.figure(figsize=(7, 8), dpi=100)
1.4. Plot
plt.plot(x, y, "bo-", label=label)
1.5. Patch
# Create a list of Patch objects with the same colors as the bars in the bar chart
legend_elements = [Patch(facecolor=color, label=label) for color, label in zip(colors, full_labels)]
# Add a legend to the plot using the given full_labels and colors from the bar chart
plt.legend(handles=legend_elements, title="Elements", loc="upper right", bbox_to_anchor=(1, 0, 0.5, 1))
A Patch object is a 2D artist in the matplotlib library. It represents a shape with a defined face color and edge color, which can be drawn on a plot. Patches are used to create various shapes, such as rectangles, circles, polygons, and more. In the context of creating a custom legend for a bar chart, Patch objects are used to create small colored squares that represent each bar in the chart.
When creating a Patch object, you can specify various properties such as the face color, edge color, line style, and more. In the code you provided earlier, Patch objects were created with a specified facecolor and label. The facecolor argument sets the color of the patch, while the label argument sets the text that will be displayed next to the patch in the legend.
Once you have created a list of Patch objects, you can pass that list to the handles argument of the plt.legend() function to create a custom legend for your plot. Each patch in the list will be displayed in the legend along with its corresponding label.