To improve the visibility of the text annotations on the bars of size 1, you can adjust the position of the text annotations to ensure they are more readable. Here are a few suggestions:
-
Offset the Text Position:
Instead of placing the text directly on top of the bar, you can add a small vertical offset to the text position for the smaller bars. This will help ensure that the text is not cramped against the bar.
Modify the text annotation line as follows:
plt.text(bar.get_x() + bar.get_width() / 2, bottom[i] + count + 2, # Add a small offset (e.g., +2)
str(count),
ha='center', va='bottom', fontsize=10, color='black')
-
Increase Font Size for Small Bars:
You can also increase the font size specifically for the smaller bars to make them more legible. You can check the height of the bar and adjust the font size accordingly:
font_size = 10 if count > 5 else 12 # Increase font size for small counts
plt.text(bar.get_x() + bar.get_width() / 2, bottom[i] + count + 2,
str(count),
ha='center', va='bottom', fontsize=font_size, color='black')
-
Use a Different Color or Style for Small Bars:
If the bars are too small, you might consider changing the color or style of the text for better visibility. For example, you could use a bold font or a contrasting color.
plt.text(bar.get_x() + bar.get_width() / 2, bottom[i] + count + 2,
str(count),
ha='center', va='bottom', fontsize=10, color='red', fontweight='bold') # Change color and make it bold
-
Add a Minimum Height for Text Placement:
You can also set a minimum height for the bars below which the text will not be displayed, or will be displayed at a fixed height.
if count > 0: # Only annotate if the count is greater than 0
text_y_position = bottom[i] + count + (2 if count > 5 else 5) # Adjust based on count
plt.text(bar.get_x() + bar.get_width() / 2, text_y_position,
str(count),
ha='center', va='bottom', fontsize=10, color='black')
By implementing these changes, you should be able to improve the readability of the text annotations on the smaller bars in your stacked bar chart.