【问题标题】:matplotlib: histogram is not displaying correctlymatplotlib:直方图显示不正确
【发布时间】:2021-02-15 02:23:15
【问题描述】:

我从一个包含我需要分析的信息的 csv 文件中提取了某些数据。把它们做成一个DataFrame。然后根据它们所在的“reg”区域类型对它们进行分组。

datafileR = datafile = pd.read_csv("pixel_data.csv")
datafileR = pd.DataFrame(datafileR)
### Counting the number of each rows based on the "Reg":
datafileR["Reg"].value_counts()

这是我收到的结果: enter image description here

根据数据框中的 Reg 列创建一个名为 region 的组:datafileR:

region = datafileR.groupby(["Reg"])

现在在直方图中绘制它们:

sns.set_theme()
plt.hist(datafileR["Reg"].value_counts(), bins=[70,100,130,160,190],color=["grey"],
         histtype='bar', align='mid', orientation='vertical', rwidth=0.85)

这是我收到的图像,但 x 轴上应该有五个类别(中东和北非、非洲(不包括 MENA)、亚洲和太平洋、欧洲和欧亚大陆以及跨区域)。我不确定什么时候出错。同时,如何更改 y 轴上的状态以显示实际数字? enter image description here

【问题讨论】:

    标签: dataframe matplotlib histogram


    【解决方案1】:

    您正在尝试绘制条形图,而不是直方图。请参考https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

    datafileR = pd.DataFrame({'reg': np.random.choice(['Asia','Africa','Europe'], size=1000)})
    df = datafileR['reg'].value_counts()
    plt.bar(x=df.index, height=df.values)
    

    您还可以使用 pandas 的绘图功能:

    df.plot.bar()
    plt.tight_layout()
    

    【讨论】:

    • 这是一个点!非常感谢!
    • 不客气。如果该解决方案解决了您的问题,请考虑使用左侧的复选标记接受答案以关闭该主题。见What should I do when someone answers my question?
    • 我对您提供的解决方案投了赞成票。尽管我确实有另一个关于将不同索引绘制到条形图中的问题。将打开另一个关于它的线程。谢谢你,Diziet。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2016-08-29
    • 2017-11-24
    • 2019-07-11
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多