3

I'm making a histogram in matplotlib and the text label for each bin are overlapping on each other like this: enter image description here

I tried to rotate the labels on the x-axis by following another solution

cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()

But I get error message 'tuple' object has no attribute 'set_xticklabels'. Why? How do I solve this problem? Alternatively, how can I "transpose" the plot so the labels are on the vertical axis?

versatile parsley
  • 411
  • 2
  • 6
  • 15

4 Answers4

1

Here you go. I lumped both answers in one example:

# create figure and ax objects, it is a good practice to always start with this
fig, ax = plt.subplots()

# then plot histogram using axis
# note that you can change orientation using keyword
ax.hist(np.random.rand(100), bins=10, orientation="horizontal")

# get_xticklabels() actually gets you an iterable, so you need to rotate each label
for tick in ax.get_xticklabels():
    tick.set_rotation(45)

It produces the graph with rotated x-ticks and horizontal histogram. enter image description here

Oleg Medvedyev
  • 1,574
  • 14
  • 16
1

The return value of plt.hist is not what you use to run the function set_xticklabels:

What's running that function is a matplotlib.axes._subplots.AxesSubplot, which you can get from here:

fig, ax = plt.subplots(1, 1)
cuisine_hist = ax.hist(train.cuisine, bins=100)
ax.set_xticklabels(rotation=45)
plt.show()

From the "help" of plt.hist:

Returns
-------
n : array or list of arrays
    The values of the histogram bins. See *normed* or *density*

bins : array
    The edges of the bins. ...

patches : list or list of lists
   ...
Scott Staniewicz
  • 712
  • 6
  • 14
0

This might be helpful since it is about rotating labels.

import matplotlib.pyplot as plt


x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()

so I think

plt.xticks(x, labels, rotation='vertical')

is the important line right here.

Ironlors
  • 173
  • 3
  • 19
0

just this simple line would do the trick

plt.xticks(rotation=45)
DataYoda
  • 771
  • 5
  • 18