Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill matplotlib bars with a gradient?

I would be very interested in filling matplotlib/seaborn bars of a barplot with different gradients exactly like done here (not with matplotlib as far as I understood): enter image description here

I have also checked this related topic Pyplot: vertical gradient fill under curve?.

Is this only possible via gr-framework: enter image description here or are there alternative strategies?

like image 473
cattt84 Avatar asked Aug 08 '16 13:08

cattt84


People also ask

How do I get the gradient color in Matplotlib?

MatPlotLib with Python Create x, y and c data points, using numpy. Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'. To display the figure, use the show() method.

How do I assign a color to each bar in Matplotlib?

To set different colors for bars in a Bar Plot using Matplotlib PyPlot API, call matplotlib. pyplot. bar() function, and pass required color values, as list, to color parameter of bar() function.


1 Answers

Just as depicted in Pyplot: vertical gradient fill under curve? one may use an image to create a gradient plot.

Since bars are rectangular the extent of the image can be directly set to the bar's position and size. One can loop over all bars and create an image at the respective position. The result is a gradient bar plot.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar = ax.bar([1,2,3,4,5,6],[4,5,6,3,7,5])

def gradientbars(bars):
    grad = np.atleast_2d(np.linspace(0,1,256)).T
    ax = bars[0].axes
    lim = ax.get_xlim()+ax.get_ylim()
    for bar in bars:
        bar.set_zorder(1)
        bar.set_facecolor("none")
        x,y = bar.get_xy()
        w, h = bar.get_width(), bar.get_height()
        ax.imshow(grad, extent=[x,x+w,y,y+h], aspect="auto", zorder=0)
    ax.axis(lim)

gradientbars(bar)

plt.show() 

enter image description here

like image 85
ImportanceOfBeingErnest Avatar answered Sep 19 '22 11:09

ImportanceOfBeingErnest