Skip to main content
 首页 » 编程设计

Python/Pandas之当 x 值为 "range"而不是整数时,将 y 值最小值设置为 0

2024年09月07日13cyq1162

所以我正在创建一个柱形图,这是我的代码:

dataset = {'Year': ["1950-1955", "1955-1960", "1960-1965", "1965-1970", "1970-1975", "1975-1980", "1980-1985", "1985-1990","1990-1995", "1995-2000", "2000-2005", "2005-2010", "2010-2015", "2015-2020"], 
         'Fertility Rate': ['7.45 ','7.45', '7.45' ,'7.45' ,'7.45', '7.45' ,'7.45', '7.469' ,'7.654', '7.182' ,'6.371' ,'5.255' ,'4.412' ,'3.713']} 
 
df3 = pd.DataFrame.from_dict(dataset) 
df4 = df3[["Year", "Fertility Rate"]] 
 
plt.bar(df4['Year'], df4['Fertility Rate']) 
plt.title('Brazil') 
plt.xticks(df4['Year'], rotation=90) 
plt.xlabel('Year Range') 
plt.ylabel('Fertility Rate') 
plt.ylim('0.0','10.0') 
plt.tight_layout() 
plt.show() 

Df2/Df1 和 df 用于从 CSV 文件中获取此数据,我刚刚从中创建了一个数据集。我正在尝试做两件事,确保 y 值从 0 开始并且最大值为 10。这是图像:

如果我删除行“plt.ylim('0.0','10.0')”,我会得到:

我知道如果我将这个添加到 df4 中:

df4 = df3[["Year", "Fertility Rate"]].astype(int) 

它会自动将我的 y 值设置为零。但是,由于我的 x 值不是整数,它们是“范围”,这不起作用。

问题:当使用日期“范围”而非整数的 x 值时,如何将 y 值的最小值设置为 0 并设置 y 最大值?

我在 Python API 上找不到类似的问题。

请您参考如下方法:

你在不该用的地方使用了字符串

# Notice I wrapped your Fertility Rates in an array and made it float 
# This is sloppy, fix it up on your side 
dataset = {'Year': ["1950-1955", "1955-1960", "1960-1965", "1965-1970", "1970-1975", "1975-1980", "1980-1985", "1985-1990","1990-1995", "1995-2000", "2000-2005", "2005-2010", "2010-2015", "2015-2020"], 
         'Fertility Rate': np.array(['7.45 ','7.45', '7.45' ,'7.45' ,'7.45', '7.45' ,'7.45', '7.469' ,'7.654', '7.182' ,'6.371' ,'5.255' ,'4.412' ,'3.713'], float)} 
 
df3 = pd.DataFrame.from_dict(dataset) 
df4 = df3[["Year", "Fertility Rate"]] 
 
df4.set_index('Year').plot.bar() 
 
plt.xlabel('Year Range') 
plt.ylabel('Fertility Rate') 
# You had strings in the `ylim` definition.  They need to be numbers. 
plt.ylim(0, 10) 
plt.tight_layout() 
plt.show()