所以我正在创建一个柱形图,这是我的代码:
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()
关于Python/Pandas - 当 x 值为 "range"而不是整数时,将 y 值最小值设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292066/