簡體   English   中英

matplotlib Y軸刻度與數據不匹配

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM