【问题标题】:Horizontal Bar Chart from DF in PythonPython中DF的水平条形图
【发布时间】:2020-11-08 17:54:36
【问题描述】:

所以我一直在尝试用 Python 中的 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()

这段代码给了我下图: Graph from Python

但我希望它是这样的:This graph 或者是这样的:Graph from Excel

这是变量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

【问题讨论】:

    标签: python dataframe csv graph bar-chart


    【解决方案1】:

    我在编辑器中复制并粘贴了您的代码,得到了您想要的图表。 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()
    

    结果:

    【讨论】:

    • 那行得通。但那是因为它来自字典。但是我该如何从数据框中做到这一点?
    • 图表中的 Y 轴值恰好与您在问题中打印的数据框的顺序相同。尝试重置数据框的索引,看看它是否有任何改变。如果没有,那么您可以查看pandas.DataFrame.to_dict,该函数允许您将数据框转换为字典然后绘制它。
    猜你喜欢
    • 2018-03-11
    • 2015-01-13
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多