Pandas / Python - 生成图表

时间:2018-03-10 02:53:03

标签: python pandas matplotlib

所以我想从csv数据文件中生成一个图表图表,并且我一直在关注指南,但我似乎无法以这样的方式操纵我的代码以获得我想要的东西。< / p>

所以这就是我到目前为止:

from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd 
import sys 
import matplotlib 
df = pd.read_csv("TB_burden_countries_2018-03-06.csv")
df = df.set_index(['country'])
df2 = df.loc["Zimbabwe", "e_mort_num"]
df2 = df.loc["Zimbabwe", "e_mort_num"]
df = pd.DataFrame(data = df2, columns= ["e_mort_num"])
df.columns = ["Mortality"]
print(df2)

这段代码就是这样我可以选择一个特定国家(津巴布韦)并查看其人口编号(e_mort_num)。我可以写什么来生成图表图表?我一直在使用本教程:http://pbpython.com/simple-graphing-pandas.html,但我在操作变量名称方面遇到了麻烦,我不太清楚我应该做什么。如果您需要更多信息,请说明。谢谢你的帮助!

感兴趣的CSV位:

  Country   Year    Mortality
    Zimbabwe    2000    20000
    Zimbabwe    2001    18000
    Zimbabwe    2002    17000
    Zimbabwe    2003    19000
    Zimbabwe    2004    19000
    Zimbabwe    2005    22000
    Zimbabwe    2006    24000
    Zimbabwe    2007    24000
    Zimbabwe    2008    23000
    Zimbabwe    2009    17000
    Zimbabwe    2010    13000
    Zimbabwe    2011    14000
    Zimbabwe    2012    14000
    Zimbabwe    2013    11000
    Zimbabwe    2014    11000
    Zimbabwe    2015    9000
    Zimbabwe    2016    5600

1 个答案:

答案 0 :(得分:1)

假设您的数据框如下所示:

>>> df
     Country  Year  Mortality
0   Zimbabwe  2000      20000
1   Zimbabwe  2001      18000
2   Zimbabwe  2002      17000
3   Zimbabwe  2003      19000
4   Zimbabwe  2004      19000
5   Zimbabwe  2005      22000
6   Zimbabwe  2006      24000
7   Zimbabwe  2007      24000
8   Zimbabwe  2008      23000
9   Zimbabwe  2009      17000
10  Zimbabwe  2010      13000
11  Zimbabwe  2011      14000
12  Zimbabwe  2012      14000
13  Zimbabwe  2013      11000
14  Zimbabwe  2014      11000
15  Zimbabwe  2015       9000
16  Zimbabwe  2016       5600

您可以使用以下代码获取条形图:

# Plot mortality per year:
plt.bar(df['Year'], df['Mortality'])
# Set plot title
plt.title('Zimbabwe')
# Set the "xticks", for barplots, this is the labels on your x axis 
plt.xticks(df['Year'], rotation=90)
# Set the name of the x axis
plt.xlabel('Year')
# Set the name of the y axis
plt.ylabel('Mortality')
# tight_layout makes it nicer for reading and saving
plt.tight_layout()
# Show your plot
plt.show()

这给了你:

enter image description here