I have successfully created a bar chart using Python and Matplotlib. I have managed to give the bars a background color and the values a color. I have also managed to x and y tick labels color (category labels color).
The next thing I want to do are the following four changes:
- Set color of the "top" and "right" to blank
- Set color of the "bottom" (x-axis) and "left" (y-axis) to grey
Code:
#
# File: bar.py
# Version 1
# License: https://opensource.org/licenses/GPL-3.0 GNU Public License
#
import matplotlib
import matplotlib.pyplot as plt
def bar(category_labels: list = ["A", "B", "C", "D"],
category_labels_color: str = "grey",
data: list = [3, 8, 1, 10],
bar_background_color: str = "red",
bar_text_color: str = "white",
direction: str = "vertical",
x_labels_rotation: int = 0,
figsize: tuple = (18, 5),
file_path: str = ".",
file_name: str = "bar.png"):
"""
Documentation: https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_label_demo.html
"""
# Debugging
print(f"bar() :: data={data}")
print(f"bar() :: category_labels={category_labels}")
print(f"bar() :: bar_background_color={bar_background_color}")
print(f"bar() :: bar_text_color={bar_text_color}")
# Use agg
matplotlib.use('Agg')
# Draw bar
fig, ax = plt.subplots(figsize=figsize)
if direction == "vertical":
bars = ax.bar(category_labels, data, color=bar_background_color)
else:
bars = ax.barh(category_labels, data, color=bar_background_color)
# Add labels to bar
ax.bar_label(bars, label_type='center', color=bar_text_color)
# X and Y labels color + rotation
plt.setp(ax.get_xticklabels(), fontsize=10, rotation=x_labels_rotation, color=category_labels_color)
plt.setp(ax.get_yticklabels(), fontsize=10, color=category_labels_color)
# Set grid color
plt.rcParams.update({"axes.grid": False, "grid.color": "#cccccc"})
# Two lines to make our compiler able to draw:
plt.savefig(f"{file_path}/{file_name}", bbox_inches='tight', dpi=200)
fig.clear()
if __name__ == '__main__':
category_labels = ['Dec 2022', 'Jan 2023', 'Feb 2023']
data = [34, 58, 7]
bar_background_color= "#4f0176"
bar_text_color = "white"
category_labels_color = "grey"
bar(category_labels=category_labels,
data=data,
bar_background_color=bar_background_color,
bar_text_color=bar_text_color,
category_labels_color=category_labels_color,
file_path=f".",
file_name="bar.png")