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:
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 )
CodePudding user response:
- The easiest way to resolve the issue is plot
values
against anx
that is a range corresponding to thelen
ofkeys
, and then change thexticklabels
.
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)
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)
CodePudding user response:
You will want to create a broken axis.
See the docs: https://matplotlib.org/3.1.0/gallery/subplots_axes_and_figures/broken_axis.html