Proposal for a new histogram function
MaximeJabarian opened this issue · 2 comments
MaximeJabarian commented
Hello,
I'm happy to share a new cyberpunk histogram style I've created. Feel free to give me any feedback.
import numpy as np
import mplcyberpunk
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from typing import Optional, Union, Tuple
# Define the gradient histogram function
def add_gradient_bar_glow(ax: Optional[plt.Axes] = None, bars=None) -> None:
# Number of shades for the gradient
n_shades = 150
# Get the current axis if no axis is provided
if not ax:
ax = plt.gca()
# Loop through each bar in the bar plot
for bar in bars:
# Get the x and y coordinates of the bar
bar_x, bar_y = bar.get_xy()
# Get the width and height of the bar
bar_width, bar_height = bar.get_width(), bar.get_height()
# Get the fill color of the bar
fill_color = bar.get_facecolor()
# Convert the fill color to RGB format
rgb = mcolors.colorConverter.to_rgb(fill_color)
# Calculate the height step for the gradient
height_step = bar_height / n_shades
# Loop through each shade in the gradient
for i in range(n_shades):
# Calculate the alpha value for the current shade
alpha = (i + 1) / n_shades
# Calculate the height of the current shade
current_height = height_step * i
# Create a gradient rectangle for the current shade
gradient_rect = plt.Rectangle((bar_x, bar_y + current_height), bar_width, height_step,
linewidth=0, alpha=alpha, color=fill_color, zorder=bar.get_zorder() - 1)
# Add the gradient rectangle to the plot
ax.add_patch(gradient_rect)
# Make the original bar transparent
bar.set_alpha(0)
# Use a cyberpunk background style
plt.style.use("cyberpunk")
# Generate colors for the bars
colors = ["#08F7FE", "#FE53BB", "#F5D300", "#00ff41", "#FF2C55"]
# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = [10, 45, 12, 67, 10]
# Create bar plot
bars = plt.bar(categories, values, color=colors, zorder=2)
# Add gradient glow inside bars
add_gradient_bar_glow(bars=bars)
# Add labels and title
plt.xlabel("Products")
plt.ylabel("Total Sales")
plt.title("Gradient Glow Bar Plot")
# Add grid with custom color
plt.grid(color='#2A3459')
plt.show()
Best wishes,
Maxime Jabarian
dhaitz commented
Hi @MaximeJabarian, this is a great suggestion! I adapted your solution to use a single mpl image filled with a color gradient instead of the individual rectangles. See #29. Feel free to try it out and comment!
MaximeJabarian commented
Hi @dhaitz, thank you for taking the time to adapt my suggestion to your project! I'm glad you found it helpful. I just checked out the implementation in #29, and the single mpl image with a color gradient is efficient and looks nice. Keep up the good work, and I look forward to contributing more :)