0

I have a graph in python I've made with matplotlib with the following code:

def to_percent(y, position):
    s = str(250 * y)
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

distance = df['Distance']
perctile = np.percentile(distance, 90) # claculates 90th percentile
bins = np.arange(0,perctile,2.5)  # creates list increasing by 2.5 to 90th percentile 
plt.hist(distance, bins = bins, normed=True)
formatter = FuncFormatter(to_percent)  #changes y axis to percent
plt.gca().yaxis.set_major_formatter(formatter)
plt.axis([0, perctile, 0, 0.10])  #Defines the axis' by the 90th percentile and 10%Relative frequency
plt.xlabel('Length of Trip (Km)')
plt.title('Relative Frequency of Trip Distances')
plt.grid(True)
plt.show()

enter image description here

What I'd like to know is, is it possible to colour the bars with gradient instead of block colour, like in this picture from excel.

enter image description here

I've not been able to find any information on this.

Josh Kidd
  • 816
  • 2
  • 14
  • 35
  • Instead of calling `hist` you could use `numpy.histogram` and plot with `bar`. Then [example from the documentation](http://matplotlib.org/examples/pylab_examples/gradient_bar.html) would apply. – wflynny Mar 06 '17 at 16:35
  • Possible duplicate of [How to fill matplotlib bars with a gradient?](http://stackoverflow.com/questions/38830250/how-to-fill-matplotlib-bars-with-a-gradient) – wflynny Mar 06 '17 at 16:37

1 Answers1

1

Take a look at the gradient_bar.py example from the matplotlib documentation.

The basic idea is that you don't use the hist() method from pyplot, but build the barchart yourself by using imshow() instead. The first argument to imshow() contains the color map which will be displayed inside of the box specified by the extent argmument.

Here's a simplified version of the example cited above that should get you on the track. It uses the values from your Excel example, and a color map that uses the CSS colors 'dodgerblue' and 'royalblue' for a linear gradient.

from matplotlib import pyplot as plt
from matplotlib import colors as mcolors

values = [22, 15, 14, 10, 7, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1, 7]

# set up xlim and ylim for the plot axes:
ax = plt.gca()
ax.set_xlim(0, len(values))
ax.set_ylim(0, max(values))

# Define start and end color as RGB values. The names are standard CSS color
# codes.
start_color = mcolors.hex2color(mcolors.cnames["dodgerblue"])
end_color = mcolors.hex2color(mcolors.cnames["royalblue"])

# color map:
img = [[start_color], [end_color]]

for x, y in enumerate(values):
    # draw an 'image' using the color map at the 
    # given coordinates
    ax.imshow(img, extent=(x, x + 1, 0, y))

plt.show()
Schmuddi
  • 1,995
  • 21
  • 35