我确实喜欢在此条形图的输出上显示条形的高度编号,并且还能够在条形图上包括要用零表示的缺失值。这是我的数据集:
# intialise data of lists.
data = {'Hospital_name':['Jootrh Hospital', 'Jootrh Hospital', 'Embu Hospital', 'Embu Hospital','Bungoma Hospital', 'Bungoma Hospital', 'Keru Hospital', 'Keru Hospital'],
'periodname':["18-Jul", "18-Aug", "18-Jul", "18-Aug","18-Jul", "18-Aug", "18-Jul", "18-Aug"], 'normal deliveries':[452, 458, "NAN", 45,498, 466, "NAN", 450],
'caesarian sections':[67.0, 99.0, 13.0, 13.0,60.0, 19.0, 73.0, "NAN"], 'breach delivery':[10.0, "NAN", 13.0, 137.0,100.0, "NAN", "NAN" ,197.0],
'assisted vd':["NAN", "NAN", 1.0, 37.0,1.0, "NAN", 1.0, 37.0]}
# Create DataFrame
df = pd.DataFrame(data)
df
这是显示条形图的代码,但我想包括缺失值和条形高度值。
import numpy as np
import matplotlib.pyplot as plt
df.set_index('periodname', inplace=True)
grouped = df.groupby('Hospital_name')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,figsize=(20,50), constrained_layout=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(kind='bar',ax=ax, title=key)
ax.legend()
plt.show()
如何在条形图上包含条形高度值并包含零表示的缺失值?
预期的输出是这样的:
最佳答案
在绘制之前,您可能只用0替换了所有“ NAN”值。
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).replace("NAN",0).plot(kind='bar',ax=ax, title=key)
每个周期应产生4条。
更新资料
有关每个条的高度/值,请参见answer。
非常粗糙且存在定位问题,在您的代码中可能看起来像这样:
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,figsize=(20,50), constrained_layout=True)
x_offset = 0.02
y_offset = 0.02
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
temp = grouped.get_group(key).replace("NAN",0).plot(kind='bar',ax=ax, title=key)
for bar in temp.patches:
b = bar.get_bbox()
val = "{:+.2f}".format(b.y1 + b.y0)
ax.annotate(val, ((b.x0 + b.x1)/2 + x_offset, b.y1 + y_offset))
ax.legend()
plt.show()