如何绘制以下数据框的直方图

How to plot histogram for below Data Frame

例如这是 DataFrame

      country_code       ($) millions
0     USA                    181519.23
1     CHN                    18507.58
2     GBR                    11342.63
3     IND                    6064.06
4     CAN                        4597.90

我想绘制直方图,X 轴显示国家/地区,Y 轴显示 Y 轴上的金额,

这可能吗

我想你的意思是 条形图,你可以用 seaborn 库来完成。

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'country_code': ['USA', 'CHN', 'GBR', 'IND', 'CAN'],
                   '($) millions': [181519.23, 18507.58, 11342.63, 6064.06, 4597.90]})

print(df)
  country_code  ($) millions
0          USA     181519.23
1          CHN      18507.58
2          GBR      11342.63
3          IND       6064.06
4          CAN       4597.90

sns.barplot(x="country_code", y="($) millions", data=df)

产生以下情节。当然,还可以进行进一步的自定义,例如标题、图例、颜色、条形宽度等。

对于如下所示的数据框:

  country_code   millions
0          USA  181519.23
1          CHN   18507.58
2          GBR   11342.63
3          IND    6064.06
4          CAN    4597.90

您可以像这样绘制您想要的图形:

# Here, df is your dataframe
# Don't forget to add "from matplotlib import pyplot as plt" at the top of your code
# if you don't have it already.
# ^ this is for the plt.show()

df.plot(x='country_code', y='millions', kind='bar')
plt.show()

这将产生以下情节:

您可以在 documentation.

中查看有关 pandas' plot 函数如何工作的更多信息

备注:

虽然 Ibrahim 的回答也有效并且 seaborn 是一个很棒的库,但我建议使用 pandas' 自己的绘图函数,如果你想要的只是像这样的简单绘图,因为 seaborn 和 pandas 都依赖于在 matplotlib 上绘制绘图。
不同之处在于有 3 个库作为依赖项而不是只有两个。

此外,如果您的绘图看起来不像这个,您可以尝试在 plt.show() 之前调用 plt.tight_layout() 以使图像更适合。