matplotlib 3D散点图日期

问题描述:

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

已经尝试过并更新了问题 –

这并不总是很琐碎告诉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值,这将是一种更有意义的方式。 –

散点图期望的数。所以您可以将日期转换为数字如下:

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)