gpt4 book ai didi

python - 获取 float hbar 图上的条数的计数/总和

转载 作者:行者123 更新时间:2023-12-03 17:12:03 25 4
gpt4 key购买 nike

我目前正在使用 matplotlib.pyplot 模块来绘制 Pandas 数据框的 float 水平条形图。

我想知道如何在特定段上添加一个带有条形总和/计数的附加条形。换句话说,从下面的代码和图中,我想构建一个数据框作为输出:

KP 0.0 to KP 0.1  : 1 bar
KP 0.1 to KP 0.5 : 2 bars
KP 0.5 to KP 0.55 : 3 bars
KP 0.55 to KP 0.7 : 2 bars

ETC...

问候,

Image plot
import pandas as pd
import matplotlib.pyplot as plt

#Create the pandas dataframe
d = {'KP_from' : [0.12, 0.84, 0.5, 0.7], 'KP_to' : [0.55, 0.05, 0.8, 0.75]}
df = pd.DataFrame(data = d)

#Create relavant variables for the floating hbar plot
start = df[['KP_from','KP_to']].min(axis = 1)
mid = df[['KP_from','KP_to']].mean(axis = 1)
width = abs(df.KP_from - df.KP_to)
yval = range(df.shape[0])

df['Direction'] = ['->' if df.KP_from.iloc[i] < df.KP_to.iloc[i] else '<-' for i in yval]

#Create the mpl figure : floating hbar plot
plt.figure()
plt.xlabel('KP')
plt.barh(y = yval, left = start, width = width)
#Add direction arrows at the center of the floating hbar
for i in yval:
plt.annotate(df.Direction.iloc[i], xy = (mid[i], yval[i]), va = 'center', ha = 'center')
plt.show()

最佳答案

这是另一种方法。正如其他人已经指出的那样,这首先是一个可以在没有条形图的情况下解决的交叉问题。

def is_present(i_start, i_end, start, end):
return (
((start <= i_start) & (end > i_start)) |
((start > i_start) & (end <= i_end))
)


# Create the pandas dataframe
d = {'KP_from': [0.12, 0.84, 0.5, 0.7], 'KP_to': [0.55, 0.05, 0.8, 0.75]}

intervals = sorted(set(d['KP_from'] + d['KP_to']))
n_bins = [
sum([is_present(i, j, s, e) for s, e in zip(d['KP_from'], d['KP_to'])])
for i, j in zip(intervals, intervals[1:])
]

for i, j, c in zip(intervals, intervals[1:], n_bins):
print(f'KP {i} to KP {j} \t: {c} bars')

关于python - 获取 float hbar 图上的条数的计数/总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61677945/

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