【问题标题】:How to load data for a barplot from a dataframe using matplotlib如何使用 matplotlib 从数据框中加载条形图的数据
【发布时间】:2019-09-25 07:52:52
【问题描述】:

所以我有一个名为 df1 的数据框,我使用 pandas 将 CSV 文件导入到我的 Jupyter 笔记本中。我现在想以条形图的形式显示这个数据框的结果。目前我只是通过插入这样的数字手动完成:data = [120,52,50]。如何改为引用数据框 df1?我试过了,但似乎没有它应该的那么简单。

这是名为df1的数据框:

+---+---------+---------+
|   | column1 | column2 |
+---+---------+---------+
| 0 |      A  |   120   |
| 1 |      B  |   52    |
| 2 |      C  |   50    |
+---+---------+---------+
    import matplotlib, matplotlib.pyplot as plt, numpy as np, random as rd, 
    pandas as pd, seaborn as sns
    %matplotlib inline

# import CSV to dataframe

    df1 = pd.read_csv("test1.csv")
    df1

# generate barplot

    data = [120,52,50]
    columns = 0,1,2
    bars = ("bar1", "bar2", "bar3")
    plt.figure(figsize = (8,6))
    b = plt.bar(columns,data,width = 0.8, color = ('#569cff','#82b5ff','#b5d1ff'))
    plt.xticks(columns,bars)
    plt.legend(b,bars,fontsize=14)
    plt.title("title goes here",fontsize=16)
    plt.ylabel('y label',fontsize=12)
    plt.xlabel('x label',fontsize=12)
    plt.show()

【问题讨论】:

    标签: python pandas dataframe matplotlib bar-chart


    【解决方案1】:

    如果您只是在寻找简单的条形图,请尝试:

    df=pd.DataFrame({'column1': ('A','B','C'),'column2':(120,52,50)}).set_index('column1')
    df.plot(kind='bar')
    

    【讨论】:

    • 但是我该怎么做才能不必手动输入数字?应该使用数据框中的内容生成条形图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2021-02-12
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多