简体   繁体   中英

How can I change the y-limit of a graph containing a dataset with strings/floats? (Python/Pandas)

This is the relevant code:

dataset = {"Year": [ '1995', '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010'],
"Rate" : np.array(['1.8', '1.7', '1.7', '1.5', '1.8', '1.6', '1.6', '1.6', '1.5', '1.3', '1.3', '1.4', '1.2', '1.2', '1.2', '1.0'])}
df6 = pd.DataFrame.from_dict(dataset)
df7 = df6[["Year", "Rate"]]
plt.bar(df7['Year'], df7['Rate'])
plt.title(Ausstralia)
plt.xticks(df6['Year'], rotation=90)
plt.xlabel('Year')
plt.ylabel('Rate')
plt.show()

This is what the graph looks like:

Aus Graph No 0 y轴

Normally, I would chuck in .astype(int) on df7, when I work with integar values. When I had another dataset that looked similar to this, I just used the np.array for the floats. But with this one, it doesn't seem to be working, and I'm unable to set a y-limit, when I use plt.ylim(0,2) .

Question : How can I fix this graph, with y-value range of 0 to 2? And what exactly have I overlooked that is causing the graph to be the way it is?

The python API does not contain a similar question, as some of the questions ask for columns that contain both strings and floats, whereas I have different columns contain either a string or float.

Using your code as a base I was able to achieve what you mentioned (plot the data with the Y-axis going from 0.0 to 2.0) by adjusting the line where you declare your np.array, adding the "dtype" parameter, in order to cast the string values to float.

"Rate" : np.array(object=['1.8', '1.7', '1.7', '1.5', '1.8', '1.6', '1.6', '1.6', '1.5', '1.3', '1.3', '1.4', '1.2', '1.2', '1.2', '1.0'], dtype=float)}

and the usual ylim(ymin=0.0,ymax=2.0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM