k3513662
k3513662

Reputation: 69

matplotlib.pyplot plot the wrong order of y-label

I tried to plot a bar figure and I want x-label to remain the specific order, so I use set_xticklabels. However, the result turns out the y-value didn't match the x-label.

import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(A, B)
ax1.set_xticklabels(A)
plt.title("Animals")
plt.show()

The expected result is Dog=26 Cat=39 Fish=10 Bird=20, but the result I got is Dog=20 Cat=39 Fish=26 Bird=20.

Here is one answer I found. However, if I use this method I cannot keep the original order I want.

import itertools
import matplotlib.pyplot as plt   
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
lists = sorted(itertools.izip(*[A, B]))
new_x, new_y = list(itertools.izip(*lists))
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(new_x, new_y )
ax1.set_xticklabels(new_x)
plt.title("Animals")
plt.show()

Is there any way I can keep the original order of x-label and make y value match with x?

Upvotes: 2

Views: 2387

Answers (3)

Vpalakkat
Vpalakkat

Reputation: 136

This code will serve the purpose,

import numpy as np
import matplotlib.pyplot as plt

A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]

y_pos = np.arange(len(A))

plt.bar(y_pos, B)
plt.xticks(y_pos, A)
plt.title("Animals")
plt.show()

click here to view output

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339775

In matplotlib 2.2 you can just plot those lists as they are and get the correct result.

import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]

plt.bar(A, B)

plt.title("Animals")
plt.show()

enter image description here

Upvotes: 0

passs
passs

Reputation: 53

Why don't you use pandas for storing your data:

import pandas as pd
import matplotlib

A= ['Dog','Cat','Fish','Bird']
B= [26,39,10,20]
ser = pd.Series(index=A, values=B)

ax = ser.loc[A].plot(kind='bar', legend=False)
ax.set_ylabel("Value")
ax.set_xlabel("Animals")

plt.show()

Upvotes: 2

Related Questions