How to Create Beautiful Bar Charts with Seaborn and Matplotlib (Including Animation) | by Oscar Leo | Jun, 2023


Step 4: Adding icons

Adding images and icons to charts is fun but tricky. It’s not always straightforward to put them in the perfect location or with the ideal size.

The following function adds icons to the end of each bar in my graph by using xycoords="data" and the values from my DataFrame.

The boxstyle parameter inside bboxprops creates a white circular background.

def add_bar_icons(ax, row, background_color, zoom, pad):
for index, (name, value) in enumerate(row.items()):
icon = plt.imread("./icons/{}.png".format(name.lower()))
image = OffsetImage(icon, zoom=zoom, interpolation="lanczos", resample=True, visible=True)
image.image.axes = ax

ax.add_artist(AnnotationBbox(
image, (value, index), frameon=True,
xycoords="data",
bboxprops={
"facecolor": "#fff",
"linewidth": 3,
"edgecolor": background_color,
"boxstyle": "circle, pad={}".format(pad),
}
))

I want to put the icon on a white circle and add a border in the same dark purple as the chart background.

So far, I haven’t found a good way to handle the zoom parameter dynamically, so I tune it manually to get the correct sizes.

Now my code for creating the chart looks like this.

row = df.iloc[-1]

fig = plt.figure(figsize=(12, 7))
ax = create_bar_chart(row, color=bar_color)

# New functions
format_axes(ax)
add_bar_icons(ax, row, background_color, zoom=0.09, pad=0.9)

plt.title("Total Number of Stars on GitHub", fontsize=34, y=1.2, x=0.46)
plt.tight_layout()
plt.show()

And this is what I get.

Bar chart created by the author

To add the star, I’ve created another function that adds a custom icon anywhere on the chart using xycoords="axes fraction".

def add_icon(ax, icon_name, x, y, zoom):
icon = plt.imread("./icons/{}.png".format(icon_name))
image = OffsetImage(icon, zoom=zoom, interpolation="lanczos", resample=True, visible=True)
image.image.axes = ax

ax.add_artist(AnnotationBbox(
image, (x, y), frameon=False,
xycoords="axes fraction",
))

In this next trick, I make room for the star icon by adding additional spaces to the title and adjusting the x and y parameters to place the icon in the correct location.

row = df.iloc[-1]

fig = plt.figure(figsize=(12, 7))
ax = create_bar_chart(row, color=bar_color)

# New functions
format_axes(ax)
add_bar_icons(ax, row, background_color, zoom=0.09, pad=0.9)
add_icon(ax, "star", x=0.46, y=1.26, zoom=0.13)

plt.title("Total Number of Stars on GitHub", fontsize=34, y=1.2, x=0.46)
plt.tight_layout()
plt.show()

Now our bar chart looks like this, and we’re almost finished.

Bar chart created by the author

It’s looking excellent, but now I want to turn the chart into a more versatile format.

And let’s do something about that squeezed look by adding some padding.



Source link

Leave a Comment