Michael Gao
Michael Gao

Reputation: 79

Advanced horizontal bar chart with Python?

I want to make a graph like the two below. How can I achieve that with python? I am sorry that I can´t provide any implementation because I don´t have any idea at all. I think my question is something different to this.

https://matplotlib.org/gallery/lines_bars_and_markers/barh.html#sphx-glr-gallery-lines-bars-and-markers-barh-py

Could someone give me some suggestions with just some simple numbers?

enter image description here

enter image description here

Upvotes: 2

Views: 1026

Answers (1)

JohanC
JohanC

Reputation: 80309

The tutorial for vertical gradient bars can be adapted to draw horizontal bars with the darkest spot in the middle:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as mcolors
import numpy as np

def hor_gradient_image(ax, extent, darkest, **kwargs):
    '''
    puts a horizontal gradient in the rectangle defined by extent (x0, x1, y0, y1)
    darkest is a number between 0 (left) and 1 (right) setting the spot where the gradient will be darkest
    '''
    ax = ax or plt.gca()
    img = np.interp(np.linspace(0, 1, 100), [0, darkest, 1], [0, 1, 0]).reshape(1, -1)
    return ax.imshow(img, extent=extent, interpolation='bilinear', vmin=0, vmax=1, **kwargs)

def gradient_hbar(y, x0, x1, ax=None, height=0.8, darkest=0.5, cmap=plt.cm.PuBu):
    hor_gradient_image(ax, extent=(x0, x1, y - height / 2, y + height / 2), cmap=cmap, darkest=darkest)
    rect = mpatches.Rectangle((x0, y - height / 2), x1 - x0, height, edgecolor='black', facecolor='none')
    ax.add_patch(rect)

# cmap = mcolors.LinearSegmentedColormap.from_list('turq', ['paleturquoise', 'darkturquoise'])
cmap = mcolors.LinearSegmentedColormap.from_list('turq', ['#ACFAFA', '#3C9E9E'])
fig, ax = plt.subplots()
for y in range(1, 11):
    x0, x1 = np.sort(np.random.uniform(1, 9, 2))
    gradient_hbar(y, x0, x1, ax=ax, height=0.7, darkest=0.5, cmap=cmap)
ax.set_aspect('auto')
ax.use_sticky_edges = False
ax.autoscale(enable=True, tight=False)
ax.grid(axis='x')
plt.show()

example plot

Upvotes: 2

Related Questions