gpt4 book ai didi

python - 放置在时间轴上的箱线图

转载 作者:行者123 更新时间:2023-11-28 21:46:09 27 4
gpt4 key购买 nike

我想在时间轴上放置一系列 (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 )

对于每个索引,我需要制作一个箱线图,这没问题:

plt.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=ii )

enter image description here

时间版本

问题是,我需要将盒子放在时间轴上,即将盒子放在具体日期上

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 )

enter image description here

但是,如果我合并这些职位:

ax.boxplot( [ df.loc[i] for i in df.index ], vert=True, positions=dates )

我得到一个错误:

TypeError: Cannot compare type 'Timedelta' with type 'float'

查看文档显示:

plt.boxplot?

positions : array-like, default = [1, 2, ..., n]

Sets the positions of the boxes. The ticks and limits are automatically set to match the positions.


希望时间版本

此代码旨在澄清、缩小问题范围。方框应该出现在那里,即下图中蓝色点所在的位置。

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

enter image description here


有没有一种方法可以在时间轴上放置箱线图?


我正在使用:

python: 3.4.3 + numpy: 1.11.0 + pandas: 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 )

enter image description here

箱线图放置在正确的位置,但代码对我来说似乎有点麻烦。

更重要的是:x轴的单位不再是“时间”。

关于python - 放置在时间轴上的箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com