Following this question: Bar Chart with multiple labels. I tried to replicate the code with a horizontal bar chart. I would like to know how I could remove/hide the labels with No data.
So instead of this:
looks more like this:
I attach the code below.
I would appreciate it if someone could steer me in the right direction here. Thank you in advance.
Cheers
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()
CodePudding user response:
I edited your code to check if each cell value is nan
when creating the labels.
If the cell value is nan
then the label value is set to an empty string, if the cell value is not nan
then the true label is used.
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()