码:

from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
import sys
import matplotlib
import numpy as np
import pylab as pl
pl.draw()

df = pd.read_csv("TB_burden_countries_2018-03-06.csv")
df = df.set_index(["country"])
df2 = df.loc["Zimbabwe", "e_mort_num"]
df = pd.DataFrame(data = df2, columns= ["e_mort_num"])
df.columns = ["Mortality"]
print(df2)

dataset = {'Year': ["2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007","2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015","2016"],
         'Mortality': ["20000", "18000", "17000", "19000", "19000", "22000", "24000", "24000", "23000", "17000", "13000", "14000","14000", "11000", "11000", "9000","5600"]}
df3 = pd.DataFrame.from_dict(dataset)
df4 = df3[["Year", "Mortality"]]

plt.bar(df3['Year'], df3['Mortality'])
plt.title('Zimbabwe')
plt.xticks(df3['Year'], rotation=90)
plt.xlabel('Year')
plt.ylabel('Mortality')
plt.tight_layout()
plt.show()

print(df3)


输出为:

python - Python/Pandas设置y轴属性-LMLPHP

编辑:我想实现(从Excel):

python - Python/Pandas设置y轴属性-LMLPHP

问题:


如何使我的x轴或y轴从零开始?


研究:


我研究了Panda API,发现它们没有针对我的问题的实际解决方案。

最佳答案

您的问题是您的数据框列YearMortality是字符串,而matplotlib对此效果不佳,至少对于您要实现的目标而言。因此,在绘制之前将它们转换为int

df = pd.DataFrame(dataset)
df[['Year', 'Mortality']] = df[['Year', 'Mortality']].astype(int)

plt.bar(df['Year'], df['Mortality'], tick_label=df['Year'])
plt.title('Zimbabwe')
plt.xticks(df['Year'], rotation=90)
plt.xlabel('Year')
plt.ylabel('Mortality')
plt.tight_layout()
plt.show()


python - Python/Pandas设置y轴属性-LMLPHP

使用给定的数据,y轴将自动设置为从0开始。但是,您可以使用ylim参数将其更改为所需的值:例如,plt.ylim(500, 50000)会将y轴设置为从500开始并结束50000。

关于python - Python/Pandas设置y轴属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49215854/

10-14 02:58