matplotlib Y轴刻度与数据不匹配

时间:2018-04-15 23:11:52

标签: python pandas dataframe matplotlib

试图找出我在这里做错了什么,因为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,但是无法弄清楚如何做到这一点。 / p>

plot from run

1 个答案:

答案 0 :(得分:1)

无需创建日期列表。enter image description here

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

将日期设置为索引后绘制的另一种方法是使用绘图方法:

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()

enter image description here

或者更简洁:

df.plot(linewidth=2)
plt.ylabel('Bandwidth Usage')
plt.show()

enter image description here