1

I have a barchart, where the y axis is the list of months from Jan to Dec and the x axis values are stored in another list in corresponding order. When I plot the graph, the order of months gets mixed up.

In:  

fig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(10,5), sharex='row')

fig.suptitle("Income from members and supporters", fontsize=14)

ax1.barh(months, tag_max)
ax1.set_facecolor('white')
ax1.set_title("Maximum income from members")

ax2.barh(months, tam_max)
ax2.set_facecolor('white')
ax2.get_yaxis().set_visible(False)
ax2.set_title('Maximum income from supporters')

Out:

enter image description here

In:

    months

Out:

    ['January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December']

What can be the reason and how can i fix it? Thanks!

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • 3
    The reason is that your y axis are strings. Matplotlib then automatically sorts these alphabetically – DavidG Dec 13 '17 at 10:07

1 Answers1

1

The comment by DavidG is correct. You can get around the problem by using numerical values for your bar position and assigning the months as yticklabels

from matplotlib import pyplot as plt
import numpy as np

months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
]

tag_max = np.random.rand(len(months))
tam_max = np.random.rand(len(months))

yticks = [i for i in range(len(months))]

fig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(10,5), sharex='row')

fig.suptitle("Income from members and supporters", fontsize=14)

ax1.barh(yticks, tag_max)
ax1.set_facecolor('white')
ax1.set_title("Maximum income from members")
ax1.set_yticks(yticks)
ax1.set_yticklabels(months)


ax2.barh(yticks, tam_max)
ax2.set_facecolor('white')
ax2.get_yaxis().set_visible(False)
ax2.set_title('Maximum income from supporters')

plt.show()

This gives the following output:

result of the given code

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63