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):
I have also checked this related topic Pyplot: vertical gradient fill under curve?.
Is this only possible via gr-framework:
or are there alternative strategies?
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()
I am using seaborn barplot with the palette
option. Imagine you have a simple dataframe like:
df = pd.DataFrame({'a':[1,2,3,4,5], 'b':[10,5,2,4,5]})
using seaborn:
sns.barplot(df['a'], df['b'], palette='Blues_d')
you can obtain something like:
then you can also play with the palette
option and colormap
adding a gradient according to some data like:
sns.barplot(df['a'], df['b'], palette=cm.Blues(df['b']*10)
obtaining:
Hope that helps.
来源:https://stackoverflow.com/questions/38830250/how-to-fill-matplotlib-bars-with-a-gradient