Step 4: Including icons
Including photographs and icons to charts is enjoyable however tough. It’s not at all times easy to place them within the good location or with the best measurement.
The next operate provides icons to the top of every bar in my graph through the use of xycoords="knowledge"
and the values from my DataFrame.
The boxstyle
parameter inside bboxprops
creates a white round background.
def add_bar_icons(ax, row, background_color, zoom, pad):
for index, (identify, worth) in enumerate(row.objects()):
icon = plt.imread("./icons/{}.png".format(identify.decrease()))
picture = OffsetImage(icon, zoom=zoom, interpolation="lanczos", resample=True, seen=True)
picture.picture.axes = axax.add_artist(AnnotationBbox(
picture, (worth, index), frameon=True,
xycoords="knowledge",
bboxprops={
"facecolor": "#fff",
"linewidth": 3,
"edgecolor": background_color,
"boxstyle": "circle, pad={}".format(pad),
}
))
I need to put the icon on a white circle and add a border in the identical darkish purple because the chart background.
Up to now, I haven’t discovered a great way to deal with the zoom
parameter dynamically, so I tune it manually to get the proper sizes.
Now my code for creating the chart seems to be like this.
row = df.iloc[-1]fig = plt.determine(figsize=(12, 7))
ax = create_bar_chart(row, coloration=bar_color)
# New features
format_axes(ax)
add_bar_icons(ax, row, background_color, zoom=0.09, pad=0.9)
plt.title("Complete Variety of Stars on GitHub", fontsize=34, y=1.2, x=0.46)
plt.tight_layout()
plt.present()
And that is what I get.
So as to add the star, I’ve created one other operate that provides a customized icon anyplace on the chart utilizing xycoords="axes fraction"
.
def add_icon(ax, icon_name, x, y, zoom):
icon = plt.imread("./icons/{}.png".format(icon_name))
picture = OffsetImage(icon, zoom=zoom, interpolation="lanczos", resample=True, seen=True)
picture.picture.axes = axax.add_artist(AnnotationBbox(
picture, (x, y), frameon=False,
xycoords="axes fraction",
))
On this subsequent trick, I make room for the star icon by including further areas to the title and adjusting the x
and y
parameters to put the icon within the appropriate location.
row = df.iloc[-1]fig = plt.determine(figsize=(12, 7))
ax = create_bar_chart(row, coloration=bar_color)
# New features
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("Complete Variety of Stars on GitHub", fontsize=34, y=1.2, x=0.46)
plt.tight_layout()
plt.present()
Now our bar chart seems to be like this, and we’re nearly completed.
It’s wanting glorious, however now I need to flip the chart right into a extra versatile format.
And let’s do one thing about that squeezed look by including some padding.