【问题标题】:Barchart in matplotmatplotlib 中的条形图
【发布时间】:2018-01-22 18:05:44
【问题描述】:

我在名为 GRADES 的列中有一系列值

Grades          count       
A               38616
B               658
G               16041
P               7590
C               33

我想在 matplot 中可视化 my_data 数据集中的列 GRADE。使用以下代码得到一个空白子图:

fig, ax=plt.subplots()
ax.set(xlabel="Grade", ylabel="Count", title="Grade Distribution")
ax.bar('GRADE', align='center', data=my_data)
plt.show()

【问题讨论】:

  • 嗯,是因为你什么都没画?
  • ax.bar 的调用签名是ax.bar(x,y, *args,**kwargs),其中 x 和 y 是条形的位置和高度。 my_data 数据集是熊猫数据框吗?
  • 看起来你想使用 seaborn 语法。查看 seaborn 和 matplotlib 这两个文档,然后决定要使用哪一个。
  • @ImportanceOfBeingErnest 是的

标签: python matplotlib bar-chart


【解决方案1】:

您正在混合绘图函数的调用签名。

假设您的数据位于 pandas 数据框中。

使用熊猫绘图功能

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Grades" : list("ABGPC"),
                   "count" : [38616,658,16041,7590,33]})

df.plot(x ="Grades", y="count", kind="bar")

plt.show()

使用 matplotlib 条形图

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Grades" : list("ABGPC"),
                   "count" : [38616,658,16041,7590,33]})

fig, ax=plt.subplots()
ax.set(xlabel="Grade", ylabel="Count")
ax.bar(df["Grades"], df["count"])

plt.show()

使用 Seaborn barplot

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"Grades" : list("ABGPC"),
                   "count" : [38616,658,16041,7590,33]})

ax = sns.barplot(x="Grades", y="count", data=df)

plt.show()

【讨论】:

    【解决方案2】:

    here给出了使用bar函数的正确方法。您应该将数据传递为xy,并且成绩必须传递为tick_lable

    grades = ['A', 'B', 'C']
    x = [1, 2, 3]
    y = [5, 7, 3]
    
    fig, ax = plt.subplots()
    ax.set(xlabel="Grade", ylabel="Count", title="Grade Distribution")
    ax.bar(x, y, align='center', tick_label=grades)
    plt.show()
    

    输出

    【讨论】:

    • 你从哪里得到 x,y 列表中的值
    • @BillehSarkozy 我一开始就初始化了 x 和 y 数组。 X 只是自然数列表1,2,3,4,5...。在您的情况下,我不知道 my_data 包含什么,因此您必须从中提取 x 和标签。
    • my_data 是一个数据框,包含多个列,例如年龄、国籍、等级等
    • 您不必将该数据帧转换为 3 个等长的单独列表。 x_listy_listlabel_list
    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 2016-01-02
    • 2017-03-27
    • 1970-01-01
    • 2015-12-25
    • 2018-11-29
    • 2016-09-11
    相关资源
    最近更新 更多