Python matplotlib Y轴比例与数据不匹配

Python matplotlib Y轴比例与数据不匹配,python,pandas,dataframe,matplotlib,Python,Pandas,Dataframe,Matplotlib,试图找出我在这里做错了什么,因为y轴看起来不像我正在使用的数据。这些数据来自谷歌的工作表,似乎正确地进入了数据框 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 tim

试图找出我在这里做错了什么,因为y轴看起来不像我正在使用的数据。这些数据来自谷歌的工作表,似乎正确地进入了数据框

    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,但是我还没有弄清楚如何做到这一点


无需创建日期列表

或者,如果要将日期设置为索引:

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

或者更简洁地说:

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

我尝试了该解决方案,但侧边的数字仍然不在数据值的范围内,即0到1000之间,中间有刻度。为了避免歧义,我明确定义了上面的数据框。你能复制第一段代码并在一个新文件中尝试吗。你应该可以复制我在这里展示的图表,我可以复制你的结果。这很有帮助。我正在看我的代码。另外,验证dataframe,它看起来是一样的,只是更多的数据。KRKirov,谢谢你的示例!我确定来自GoogleSheetAPI的数据将数字格式化为字符串。我可以使用valueRenderOption输出未格式化的数字,现在只需将日期从字符串转换为datetime格式。好的,看起来你要解决你的问题了。您还可以使用pd.to\u numeric将字符串转换为数字类型。如果y轴上的刻度密度有问题,则可以在plt.show()之前使用plt.yticks(np.arange(0,1000,100)),并根据需要调整最大值和步长。请阅读。我们不能复制你的问题。例如,
值是什么?或者
datetime.strtime
?导入和缩进都是脚本的一部分。
df.plot(linewidth=2)
plt.ylabel('Bandwidth Usage')
plt.show()