2017-03-08 225 views
2

15/10/2017matplotlib 3D散點圖日期

我試圖日期的格式列表如下

from matplotlib import pyplot 
import pandas as pd 

dates = ['15/10/2016', '16/10/2016', "17/10/2015", "15/10/2014"] 
dates_formatted = [pd.to_datetime(d) for d in dates ] 
x = [1,2,3,4] 
z = [5,6,7,8] 

pyplot.scatter(x, dates_formatted, z) 
pyplot.show() 

它拋出一個錯誤TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

這表明,如果它是2D的。例如pyplot.scatter(x, dates_formatted)

我也曾嘗試以下

ax = Axes3D(fig) 
ax = fig.add_subplot(111,projection='3d') 
ax.scatter(x, dates_formatted, y) 
pyplot.show() 

它拋出一個錯誤Float() argument must be a string or number

+0

我懷疑你實際上調用了常規的'Axes'對象的散佈方法。嘗試用'ax = fig.add_subplot(111,projection ='3d')'創建一個'Axes3d'對象,然後完成你所做的事情。 –

+0

已經嘗試過並更新了問題 –

回答

5

這並不總是很瑣碎告訴matplotlib如何轉換字符串成一個座標系。爲什麼不簡單地爲軸設置自定義刻度標籤?

import pandas as pd 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 

fig = plt.figure('scatter dates') 
ax = fig.add_subplot(111, projection='3d') 
dates = ['15/10/2016', '16/10/2016', "17/10/2015", "15/10/2014"] 
dates_formatted = [pd.to_datetime(d) for d in dates ] 
x = [1,2,3,4] 
y = [9,10,11,12] 
z = [5,6,7,8] 

ax.scatter(x, y, z) 
ax.xaxis.set_ticks(x) 
ax.xaxis.set_ticklabels(dates_formatted) 
plt.show() 

enter image description here

+0

因此,如果我正確理解解決方案,'x'上的值列表只是任意數字,以便符合'scatter()'函數支持的值。此後,我們只需要爲'x'軸設置一個自定義標籤(日期)來對'值'進行排序。 –

+0

@MaTaKazer非常如此,是的。原則上,您也可以直接從時間字符串計算x值,這將是一種更有意義的方式。 –

2

散點圖期望的數。所以您可以將日期轉換爲數字如下:

y = [ (d-min(dates_formatted)).days for d in dates_formatted] 

現在你可以繪製數據

pyplot.scatter(x, y) 

對於3D繪圖,你可以嘗試這樣的事情......

import pandas as pd 
import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 

plt.ion() 
x = [1,2,3,4] 
z = [5,6,7,8] 
dates = ['15/10/2016', '16/10/2016', "17/10/2015", "15/10/2014"] 
dates_formatted = [pd.to_datetime(d) for d in dates] 

y = [ (d-min(dates_formatted)).days for d in dates_formatted] 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
plt.scatter(x, y, z) 

y軸現在在天。您可以通過查找日期字符串,並改變它變回那個......

dt = [ pd.Timedelta(d) + min(dates_formatted) for d in ax.get_yticks()] 

這些轉換成字符串......

dtStr = [d.isoformat() for d in dt] 

,將它們放回

ax.set_yticklabels(dtStr)