3

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')

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

it is impossible with the step method to plot each point horizontally. When using the pre/post arguments to where the step is truncated, and with mid both steps on each side are truncated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.