2017-04-17 51 views
0

我有以下數據 -情節時間序列散點圖

ProductName 01/01/2016 01/07/2016 01/14/2017 
ABC    12    34   51 
XYZ    9    76   12 
PQR    12    23    7 
DEF    54    4   34 

我想繪製出每一天的總銷售時間序列散點圖。我創建了以下功能 -

def scatterplot(x_data, y_data, x_label, y_label, title): 
_, ax = plt.subplots() 
ax.scatter(x_data, y_data, s = 30, color = '#539caf', alpha = 0.75) 

ax.set_title(title) 
ax.set_xlabel(x_label) 
ax.set_ylabel(y_label) 

我很困惑如何調用此函數來獲得我想要的結果。該圖應該在x軸上顯示日期,並在y上顯示總銷售額。

回答

0

如果您的數據位於pandas DataFrame中,您可以將列標題作爲x值,並將垂直軸上的數據總和(即當天銷售的產品總數)作爲y值。

import pandas as pd 
import matplotlib.pyplot as plt 

# replicate Data from question in DataFrame 
v = [[12,34,51], [9,76,12], [12,23,7], [54,4,34]] 
df = pd.DataFrame(v, columns=["01/01/2016","01/07/2016","01/14/2017"], 
         index=["ABC", "XYZ", "PQR", "DEF"]) 
print(df) 


def scatterplot(x_data, y_data, x_label, y_label, title): 
    fig, ax = plt.subplots() 
    ax.scatter(x_data, y_data, s = 30, color = '#539caf', alpha = 0.75) 

    ax.set_title(title) 
    ax.set_xlabel(x_label) 
    ax.set_ylabel(y_label) 
    fig.autofmt_xdate() 

#use column headers as x values 
x = pd.to_datetime(df.columns, format='%m/%d/%Y') 
# sum all values from DataFrame along vertical axis 
y = df.values.sum(axis=0)  
scatterplot(x,y, "x_label", "y_label", "title") 

plt.show() 

enter image description here