【发布时间】:2020-05-08 11:18:56
【问题描述】:
我目前正在使用 matplotlib.pyplot 模块绘制 pandas 数据框的浮动水平条形图。
我想知道如何添加一个附加条,其中包含特定段的条的总和/计数。换句话说,从下面的代码和图中,我想构建一个数据框作为输出:
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
等等……
问候,
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()
【问题讨论】:
标签: python pandas matplotlib