2

I am trying to make a bar chart with matplotlib for python. I can make a normal chart, but when I put it in logarithmic mode so that I can see the data better, the x-axis looks as if it is compressing. What is going on? Note: all data records have a minimum value of 1.

    x = [t[0] for t in data]
    y = [t[1]  for t in data]

    x_pos = np.arange(len(x))

    plt.bar(x_pos, y, color='blue', log=False)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.title(title)
    plt.xlim([0, len(x)])
    #plt.yscale('log')
    #plt.semilogy(x_pos, np.exp(-x_pos/5.0))
    plt.savefig(output_path + '/' + filename)

Yields: enter image description here

But just by changing log=False to log=True I get: enter image description here

What am I doing wrong? I just want to get a compressed view of the first graph on the y axis. As you can see, I also tried yscale('log') but I get the same result.

Thanks!

EDIT: Looks like it has something to do with the previous lines, when I remove the first line it works fine, but is unsorted:

data = sorted(data, key=lambda tup: tup[1], reverse=True)

    # tuples (pair,count)
    x = [t[0] for t in data]
    y = [t[1]  for t in data]

2 Answers 2

3

If you just want a log scale on the y axis and not the x use:

import matplotlib.pyplot as plt

plt.semilogy(x,y) #plots log on y axis

plt.semilogx(x,y) #plots log on x axis

Alternatively, you can just set the axis' to log:

ax = plt.subplot(224)

ax.set_xscale("log")
ax.set_yscale("log")

plt.bar(x,y)
Sign up to request clarification or add additional context in comments.

2 Comments

I have the same problem. It still compresses on the x axis, just like in my example.
I tried both methods but I get the same result. The X axis is compressed, like in my second picture.
1

It isn't compressing your x-axis; the minimum value of your second plot's y-axis is 1 (10^0), which it appears is the height of the smallest set of bars. Hence, the rightmost bars are off the y scale on your semilog plot.

Try adding, e.g.,

plt.ylim([0.1, 100])

to enforce the visibility of the rightmost bars. (A log-scale axis can't have a minimum limit of 0, for obvious reasons.)

1 Comment

Thank you, sir! That was indeed the problem!

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.