[英]How to hide/remove labels with No Data in a multiple labeled horizontal Bar Chart
关注这个问题: Bar Chart with multiple labels 。 我试图用水平条形图复制代码。 我想知道如何删除/隐藏没有数据的标签。
所以不是这个:
看起来更像这样:
我附上下面的代码。
如果有人能在这里引导我朝着正确的方向前进,我将不胜感激。 先感谢您。
干杯
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
df = pd.DataFrame(
{"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)
test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
aggfunc=np.sum)
fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
pos.append(bar.get_y()+bar.get_height()/2.)
ax.set_yticks(pos,minor=True)
lab = []
for i in range(len(pos)):
l = test.columns.values[i//len(test.index.values)]
lab.append(l)
ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)
plt.show()
plt.close()
我编辑了您的代码以检查在创建标签时每个单元格的值是否为nan
。
如果单元格值为nan
,则 label 值设置为空字符串,如果单元格值不是nan
,则使用 true label。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
df = pd.DataFrame(
{"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)
test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
aggfunc=np.sum)
fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
pos.append(bar.get_y()+bar.get_height()/2.)
ax.set_yticks(pos,minor=True)
lab = []
#EDITED FROM HERE
arr = []
for i in range(len(test.iloc[0].values)):
arr.append(test.iloc[0].values[i])
arr.append(test.iloc[1].values[i])
for i in range(len(pos)):
l = test.columns.values[i//len(test.index.values)]
val = arr[i]
if np.isnan(val):
lab.append("")
else:
lab.append(l)
#TO HERE
ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)
plt.show()
plt.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.