Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 536
Sabba Avatar asked Feb 05 '26 21:02

Sabba


2 Answers

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

like image 140
sodd Avatar answered Feb 08 '26 10:02

sodd


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.

like image 22
Pascal Bugnion Avatar answered Feb 08 '26 12:02

Pascal Bugnion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!