所以我一直在尝试用DF在DF中制作水平条形图。我成功了,但X轴上的值没有正确排列。
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
plt.rcdefaults()
fig, ax = plt.subplots()
plt.xlim(0, 14)
# data
people = (a.Ethnicity)
y_pos = np.arange(len(people))
performance = a.Value
ax.barh(y_pos, performance, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Value')
ax.set_title('Unemployment between different ethnic groups in 2004')
plt.show()
这段代码为我提供了下图:Python中的图
这是变量a:
a = df.loc[(df.Time == 2018) & (df.Region == "All") & (df.Age == "All") & (df.Sex == "All"), ["Ethnicity","Value"]]
print(a)
Ethnicity Value
32772 All 4.2
32952 Asian 6.2
33132 Asian Other 6.1
33312 Black 8.8
33492 Indian 4.3
33672 Mixed 7
33852 Other 7.5
34032 Other than White 7.1
34212 Pakistani and Bangladeshi 8.4
34392 Unknown 4.1
34572 White 3.7
34752 White British 3.8
34932 White Other 3.4
我将您的代码复制并粘贴到编辑器中,并得到了所需的图形。X轴上的值顺序正确。在我看来,可能是代码的另一部分发生了某种不正确的排序。我将您的数据复制为字典以创建数据框。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig, ax = plt.subplots()
plt.xlim(0, 100)
data = {'All': 4.2,
'Asian': 6.2,
'Asian Other': 6.1,
'Black': 8.8,
'Indian': 4.3,
'Mixed': 7,
'Other': 7.5,
'Other than White': 7.1,
'Pakistani and Bangladeshi': 8.4,
'Unknown': 4.1,
'White': 3.7,
'White British': 3.8,
'White Other': 3.4}
a = pd.DataFrame(data.items(), columns=["Ethnicity", "Value"])
people = (a.Ethnicity)
y_pos = np.arange(len(people))
performance = a.Value
ax.barh(y_pos, performance, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Value')
plt.tight_layout()
plt.show()
结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句