1

I plot two bar plots to the same ax, where the x axis contains values from 0 downwards. However, I have significant gaps in my data (like from 0 to -15), and would like to remove the empty space, so that the axis goes from 0 to -15 with no space in between - show on this image:

enter image description here

Ideally I would like to do this for all gaps. I have tried both plt.axis('tight') and fig.tight_layout(), but neither of them have worked.

Edit: sample code for a small example

keys = [0, -15, -16, -17]
values = [3, 5, 2, 1]

fig, ax = plt.subplots(ncols=1)
fig.tight_layout()

ax.bar(keys, values, 0.8, color='g', align='center')

ax.set_xticks(keys)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90 )

enter image description here

0

1 Answer 1

1
  • The easiest way to resolve the issue is plot values against an x that is a range corresponding to the len of keys, and then change the xticklabels.
import matplotlib.pyplot as plt

keys = [0, -15, -16, -17]
values = [3, 5, 2, 1]

fig, ax = plt.subplots()

# create the xticks locations
x = range(len(keys))

ax.bar(x, values, 0.8, color='g', align='center')

# set the ticks and labels
ax.set_xticks(x)
_ = ax.set_xticklabels(keys)

enter image description here

Sorting

keys = [0, -15, -16, -17]
values = [3, 5, 2, 1]

# zip, sort and unpack
keys, values = zip(*sorted(zip(keys, values)))

fig, ax = plt.subplots()

# create the xticks locations
x = range(len(keys))

ax.bar(x, values, 0.8, color='g', align='center')

# set the ticks and labels
ax.set_xticks(x)
_ = ax.set_xticklabels(keys)

enter image description here

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

Comments

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.