Sabba
Sabba

Reputation: 561

Matplotlib Bar Customization

This part of my code produces the bar chart in figure (1). I wonder how to modify it to produce the bar chart in figure (2) which is way more readable.

axs[4].set_xticks(range(N))
axs[4].set_xticklabels(words[inds],rotation = 'vertical')
axs[4].set_xlabel('word')
axs[4].set_yscale('log')
axs[4].set_ylabel('pagerank')
axs[4].set_title('Sorted PageRank biased by total word frequencies (c = '+str(c4)+')')
axs[4].bar(range(N),p4[inds],lw=2.5, align='center')

plt.subplots_adjust(hspace=.5)

plt.savefig('./figures/pageranks.pdf')

Upvotes: 3

Views: 1083

Answers (2)

sodd
sodd

Reputation: 12923

You can define your own function, and use plt.hlines to plot the horizontal lines. If you want to plot this in a certain axes, simply provide this axes as the argument to the ax parameter.

import matplotlib.pyplot as plt
import numpy as np

def bar_tops(x, y, width=0.8, align='center', ax=None, **kwargs):
    x = np.array(x)
    y = np.array(y)
    if align == 'center':
        left = x - 0.5 * width
        right = x + 0.5 * width
    elif align == 'edge':
        left = x
        right = x + width
    if ax == None:
        ax = plt.gca()
    ax.hlines(y, left, right, **kwargs)

Example usage:

bar_tops(np.arange(10), np.sort(np.random.rand(10)), lw=2)
plt.show()

Output

Upvotes: 2

Pascal Bugnion
Pascal Bugnion

Reputation: 4928

Using pylab.step instead of pylab.bar gives something a little closer to what you want. It takes the same arguments as bars but plots "steps" instead of "bars".

import pylab as p
ax = p.gca()
xbins = p.linspace(0.,10.,10)
step_heights = [10, 9, 9, 9, 7, 6, 6, 5, 4, 3]
ax.step(xbins, step_heights, linewidth=2.5, color="k",where="mid")
ax.set_ylim(0.,11.)

step-plot

You may also want to look at the somewhat more complete pylab.hist documentation.

Upvotes: 2

Related Questions