[英]matplotlib Y-axis scale does not match data
试图找出我在这里做错了什么,因为y轴看起来不像我正在使用的数据。 数据来自Google工作表,似乎正确进入了数据框。
df = pd.DataFrame.from_records(values[1:], columns=values[0])
df.set_index('date')
print(df)
datelist = df.date.tolist()
fmt = '%Y-%m-%d' # check the time format of the timestamp in the first column
x_axis = [datetime.strptime(dat, fmt) for dat in datelist]
plt.style.use('ggplot')
plt.plot(x_axis, 'usage', data=df, color='skyblue', linewidth=2, label='Daily Usage')
plt.plot(x_axis, 'currenttotal', data=df, color='yellow', linewidth=2, label='Total Usage')
plt.xlabel('Date')
plt.ylabel('Bandwidth Usage')
plt.legend(loc='upper left')
plt.savefig('todaysplot.png', dpi=300)
这是数据帧:
` date usage currenttotal
0 2017-11-08 13 328
1 2017-11-09 12 340
2 2017-11-10 12 359
3 2017-11-11 7 366`
如果您在y轴上打勾,我会在数据框的左侧获取数字,并在左侧获取0到1024之间的数字,但是还无法弄清楚该怎么做。
import pandas as pd
import matplotlib.pyplot as plt
date = ['2017-11-08', '2017-11-09', '2017-11-10', '2017-11-11']
usage = [13, 12, 12, 7]
currenttotal = [328, 340, 359, 366]
df = pd.DataFrame({'date': date, 'usage': usage, 'currenttotal': currenttotal})
df['date'] = pd.to_datetime(df['date'])
plt.style.use('ggplot')
plt.plot('date', 'usage', data=df, color='skyblue', linewidth=2, marker='D', label='Daily Usage')
plt.plot('date', 'currenttotal', data=df, color='yellow', linewidth=2, marker='o',label='Total Usage')
plt.xlabel('Date')
plt.ylabel('Bandwidth Usage')
plt.legend(loc='upper left')
plt.show()
df
Out[13]:
currenttotal date usage
0 328 2017-11-08 13
1 340 2017-11-09 12
2 359 2017-11-10 12
3 366 2017-11-11 7
或者,如果您要将日期设置为索引:
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace = True)
plt.style.use('ggplot')
plt.plot('usage', data=df, color='skyblue', linewidth=2, marker='D', label='Daily Usage')
plt.plot('currenttotal', data=df, color='yellow', linewidth=2, marker='o',label='Total Usage')
plt.xlabel('Date')
plt.ylabel('Bandwidth Usage')
plt.legend(loc='upper left')
plt.show()
df
Out[37]:
usage currenttotal
date
2017-11-08 13 328
2017-11-09 12 340
2017-11-10 12 359
2017-11-11 7 366
将日期设置为索引后进行绘图的另一种方法是使用plot方法:
plt.figure()
df['usage'].plot(c='blue', linewidth=2, marker='D', label='Daily Usage')
df['currenttotal'].plot(c='red', linewidth=2, marker='o', label='Total Usage')
plt.xlabel('Date')
plt.ylabel('Bandwidth Usage')
plt.legend(loc='right')
plt.show()
或更简而言之:
df.plot(linewidth=2)
plt.ylabel('Bandwidth Usage')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.