Lui*_*uis 4 python datetime matplotlib boxplot pandas
我想在时间轴上放置一系列(matplotlib)箱线图。它们是一年中不同日期进行的一系列测量。日期分布不均匀,我对随时间的变化感兴趣。
我有一个带有索引和一系列数字的 pandas DataFrame,或多或少像这样:(注意索引):
np.random.seed(12345)
data = np.array( [ np.random.normal( i, 1, 10 ) for i in range(3) ] )
ii = np.array([ 3, 5, 8 ] )
df = pd.DataFrame( data=data, index=ii )
Run Code Online (Sandbox Code Playgroud)
对于每个索引,我需要制作一个箱线图,这没有问题:
plt.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=ii )
Run Code Online (Sandbox Code Playgroud)
问题是,我需要将框放置在时间轴上,即将框放置在具体日期上
np.random.seed(12345)
data = np.array( [ np.random.normal( i, 1, 10 ) for i in range(3) ] )
dates = pd.to_datetime( [ '2015-06-01', '2015-06-15', '2015-08-30' ] )
df = pd.DataFrame( data=data, index=dates )
plt.boxplot( [ df.loc[i] for i in df.index ], vert=True )
Run Code Online (Sandbox Code Playgroud)
但是,如果我合并这些职位:
ax.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=dates )
我收到错误:
类型错误:无法将类型“Timedelta”与类型“float”进行比较
查阅文档显示:
plt.boxplot?
位置 :类似数组,默认 = [1, 2, ..., n]
设置框的位置。价格变动和限制会自动设置以匹配仓位。
这段代码的目的是澄清、缩小问题范围。这些框应该出现在那里,下图中蓝点位于此处。
np.random.seed(12345)
data = np.array( [ np.random.normal( i, 1, 10 ) for i in range(3) ] )
dates = pd.to_datetime( [ '2015-06-01', '2015-06-15', '2015-08-30' ] )
df = pd.DataFrame( data=data, index=dates )
fig, ax = plt.subplots( figsize=(10,5) )
x1 = pd.to_datetime( '2015-05-01' )
x2 = pd.to_datetime( '2015-09-30' )
ax.set_xlim( [ x1, x2 ] )
# ax.boxplot( [ df.loc[i] for i in df.index ], vert=True ) # Does not throw error, but plots nothing (out of range)
# ax.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=dates ) # This is what I'd like (throws TypeError)
ax.plot( dates, [ df.loc[i].mean() for i in df.index ], 'o' ) # Added to clarify the positions I aim for
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以将箱线图放置在时间轴上?
我在用:
蟒蛇:3.4.3 + numpy:1.11.0 + 熊猫:0.18.0 + matplotlib:1.5.1
到目前为止,我最好的解决方案是将轴的单位转换为合适的int单位并相应地绘制所有内容。就我而言,那是几天。
np.random.seed(12345)
data = np.array( [ np.random.normal( i, 1, 10 ) for i in range(3) ] )
dates = pd.to_datetime( [ '2015-06-01', '2015-06-15', '2015-08-30' ] )
df = pd.DataFrame( data=data, index=dates )
fig, ax = plt.subplots( figsize=(10,5) )
x1 = pd.to_datetime( '2015-05-01' )
x2 = pd.to_datetime( '2015-09-30' )
pos = ( dates - x1 ).days
ax.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=pos )
ax.plot( pos, [ df.loc[i].mean() for i in df.index ], 'o' )
ax.set_xlim( [ 0, (x2-x1).days ] )
ax.set_xticklabels( dates.date, rotation=45 )
Run Code Online (Sandbox Code Playgroud)
箱线图放置在正确的位置,但代码对我来说似乎有点麻烦。
更重要的是:x轴的单位不再是“时间”。
| 归档时间: |
|
| 查看次数: |
11312 次 |
| 最近记录: |