【问题标题】:How to plot histogram for below Data Frame如何绘制以下数据框的直方图
【发布时间】:2021-09-05 03:20:14
【问题描述】:

例如这是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 轴上的金额,

这可能吗?

【问题讨论】:

  • 你的意思是像条形图吗?
  • 对于 hist:df.set_index('country_code').hist(grid=False) 和对于 bar df.set_index('country_code').plot(kind='bar')

标签: python pandas data-science


【解决方案1】:

我认为您的意思是 条形图,您可以使用 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)

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

【讨论】:

  • 您忘记了调用 sns 进行绘图的实际行。
  • 感谢指出,我已经更新了我的代码。
【解决方案2】:

对于如下所示的数据框:

  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 的绘图功能的工作原理。

注意事项:

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

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

【讨论】:

  • 如果我想在 y 轴上有自定义存储桶,例如 5000000 - 7000000, 7000000-10000000,怎么样?
  • 您可以通过在plt.show() 之前调用plt.yticks(...) 来更改Y 轴上的标记。示例:plt.yticks([5000000, 7000000, 10000000]) 将在 y 轴上为指定值生成一个带有 3 个标记的图。文档:matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.yticks.html
猜你喜欢
  • 2018-02-15
  • 2023-03-08
  • 2018-04-14
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 2015-12-31
  • 1970-01-01
相关资源
最近更新 更多