mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C'))
code 1)
count_grade = mpg['grade'].value_counts()
count_grade.plot.bar(rot=0)
plt.show()
code 2)
count_grade = mpg['grade'].value_counts().sort_index() # method chaining
count_grade.plot.bar(rot=0)
plt.show()
reference) count_grade -> 'A' : 10, 'B' : 118, 'C' : 106
(in VSCode) The execution result is different with and without the code 1). When I only run code 2) without code 1), A is more than 120 instead of 10 (in graph) enter image description here However, when the two codes are executed together, the result is normally output as a result of only 'A', 'B', and 'C' being sorted. enter image description here
(in Colab)
mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >=20, 'B', 'C'))
count_grade = mpg['grade'].value_counts().sort_index()
print(count_grade)
count_grade.plot.bar(rot=0)
When I put this code in one block and run it, the results are output strangely. enter image description here
However, running the last line separately solves the problem enter image description here
I'd like to know what the problem is. please help me
expecting :
but my result : 
mpg.head().to_dict()
model': {0: 'a4', 1: 'a4', 2: 'a4', 3: 'a4', 4: 'a4'}, 'displ': {0: 1.8, 1: 1.8, 2: 2.0, 3: 2.0, 4: 2.8}, 'year': {0: 1999, 1: 1999, 2: 2008, 3: 2008, 4: 1999}, 'cyl': {0: 4, 1: 4, 2: 4, 3: 4, 4: 6}, 'trans': {0: 'auto(l5)', 1: 'manual(m5)', 2: 'manual(m6)', 3: 'auto(av)', 4: 'auto(l5)'}, 'drv': {0: 'f', 1: 'f', 2: 'f', 3: 'f', 4: 'f'}, 'cty': {0: 18, 1: 21, 2: 20, 3: 21, 4: 16}, 'hwy': {0: 29, 1: 29, 2: 31, 3: 30, 4: 26}, 'fl': {0: 'p', 1: 'p', 2: 'p', 3: 'p', 4: 'p'}, 'category': {0: 'compact', 1: 'compact', 2: 'compact', 3: 'compact', 4: 'compact'}, 'total': {0: 23.5, 1: 25.0, 2: 25.5, 3: 25.5, 4: 21.0}, 'grade': {0: 'B', 1: 'B', 2: 'B', 3: 'B', 4: 'B'}}
** my full code **
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
mpg = pd.read_csv('mpg.csv')
mpg['total'] = (mpg['cty'] + mpg['hwy']) / 2
mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C'))
count_grade = mpg['grade'].value_counts()
count_grade.plot.bar(rot=0)
plt.show()
count_grade = mpg['grade'].value_counts().sort_index()
count_grade.plot.bar(rot=0)
print(count_grade)
plt.show()