我试图绘制一个x-y图,用x或y作为日期变量,并使用第三个变量为点着色。 如果3个变量都不是日期,我设法做到了,使用:
import matplotlib, datetime
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
todayTime=datetime.datetime.now();
df = pd.DataFrame({'x': [todayTime+datetime.timedelta(hours=i) for i in range(10)], 'y': range(10),'z' : [2*j for j in range(10)]});
xAlt=[0.5*i for i in range(10)];
fig, ax = plt.subplots()
ax.scatter(df['x'],df['y'],s=20,c=df['z'], marker = 'o', cmap = cm.jet )
plt.show()
搜索之后,我发现对于正常情节,我们必须使用plot_date()。不幸的是,我还没有能够为这些点着色。 有人能帮助我吗?
这是一个小例子:
string lb_BS_ID = ((Label)GridView1.FindControl("lblBSID")).Text;
您可以用xAlt替换df [' x']以查看所需的结果
谢谢
答案 0 :(得分:1)
据我所知,必须使用scatter
来为你描述的点着色。一种解决方法可能是使用FuncFormatter
将刻度标签转换为x轴上的时间。下面的代码将日期转换为数字,制作散点图,并使用FuncFormatter
将刻度标签转换回日期。
import matplotlib, datetime
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
from matplotlib.ticker import FuncFormatter
todayTime=datetime.datetime.now()
df = pd.DataFrame({'x': [todayTime+datetime.timedelta(hours=i) for i in range(10)], 'y': range(10),'z' : [2*j for j in range(10)]})
def my_formatter(x, pos=None):
d = matplotlib.dates.num2date(x)
if len(str(d.minute)) == 1:
mn = '0{}'.format(d.minute)
else:
mn = str(d.minute)
if len(str(d.hour)) == 1:
hr = '0{}'.format(d.hour)
else:
hr = str(d.hour)
return hr+':'+mn
major_formatter=FuncFormatter(my_formatter)
nums = np.array([matplotlib.dates.date2num(di) for di in df['x']])
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(major_formatter)
ax.scatter(nums,df['y'],s=20,c=df['z'], marker = 'o', cmap = cm.jet )
xmin = df['x'][0]-datetime.timedelta(hours=1)
xmax = df['x'][len(df['x'])-1]+datetime.timedelta(hours=1)
ax.set_xlim((xmin,xmax))
plt.show()