Gasprices.txt 的一部分就像
04-05-1993:1.068
1993 年 4 月 12 日:1.079
1993 年 4 月 19 日:1.079
05-09-1994:1.045
1994 年 5 月 16 日:1.046
1994 年 5 月 23 日:1.05
import matplotlib.pyplot as plt
import numpy as np
with open('c:/Gasprices.txt', 'r') as file:
td = dict()
for line in file:
year = line[6:10]
price = float(line[11:])
td.setdefault(year, []).append(price)
for k, v in td.items():
Year =f'{k}'
avg_price = f'{sum(v)/ len(v)}'
print(Year, avg_price)
上面代碼的結果是
1993 1.0711538461538466
1994 1.0778653846153845
1995 1.1577115384615386
1996 1.2445283018867925
1997 1.2442499999999999
1998 1.071711538461538
1999 1.1760576923076924
2000 1.522730769230769
2001 1.4603018867924529
2002 1.385961538461538
2003 1.603019230769231
2004 1.8946923076923083
2005 2.314461538461538
2006 2.6182692307692315
2007 2.8434716981132078
2008 3.2989038461538462
2009 2.4058269230769236
2010 2.835057692307693
2011 3.576423076923077
2012 3.6796415094339627
2013 3.651441176470588
我想將此結果用于使用 matplotlib 繪制圖形。但是由于回圈,如果我使用這樣的代碼
import matplotlib.pyplot as plt
import numpy as np
with open('c:/Gasprices.txt', 'r') as file:
td = dict()
for line in file:
year = line[6:10]
price = float(line[11:])
td.setdefault(year, []).append(price)
for k, v in td.items():
Year =f'{k}'
avg_price = f'{sum(v)/ len(v)}'
print(Year, avg_price)
x=Year
y=avg_price
plt.plot(x,y, 'o--')
plt.title('Average gas price per year in US')
plt.xlabel('year')
plt.ylabel('Avg.gas price per gallon[$]')
plt.grid()
plt.xticks(np.arange(1993, 2014, 1))
plt.xticks(rotation=45)
plt.yticks(np.arange(1.0, 4.0, 0.5))
plt.tight_layout()
plt.show()
圖中僅繪制了最后一條資訊 2013 3.651441176470588。
如何將所有年份資訊和 avg_price 資訊分別放在 x 和 y 中?
uj5u.com熱心網友回復:
您需要將這些資訊添加到串列(此處x和y):
x = []
y = []
with open('c:/Gasprices.txt', 'r') as file:
td = dict()
for line in file:
year = line[6:10]
price = float(line[11:])
td.setdefault(year, []).append(price)
for k, v in td.items():
Year = f'{k}'
avg_price = f'{sum(v)/ len(v)}'
print(Year, avg_price)
x.append(Year)
y.append(avg_price)
由于您的資料是字串,因此您需要轉換它們:
x = [int(i) for i in x] # Years are int
y = [float(i) for i in y] # Prices are float
然后你可以用同樣的方式呼叫你的情節:
plt.plot(x,y, 'o--')
plt.title('Average gas price per year in US')
plt.xlabel('year')
plt.ylabel('Avg.gas price per gallon[$]')
plt.grid()
plt.xticks(np.arange(1993, 2014, 1))
plt.xticks(rotation=45)
plt.yticks(np.arange(1.0, 4.0, 0.5))
plt.tight_layout()
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473864.html
標籤:Python matplotlib 阴谋 图形 平均的
