mherzog
mherzog

Reputation: 1230

Display x-axis values on horizontal matplotlib histogram

I'd like to use matplotlib to display a horizontal histogram similar to the one below:

enter image description here

The code below works fine for vertical histograms:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'A':['Male'] * 10 + ['Female'] * 5})
plt.hist(df['A'])
plt.show()

enter image description here

The orientation='horizontal' parameter makes the bars horizontal, but clobbers the horizontal scale.

plt.hist(df['A'],orientation='horizontal')

enter image description here

The following works, but feels like a lot of work. Is there a better way?

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.set_xticks([0,5,10])
ax.set_xticklabels([0,5,10])
ax.set_yticks([0,1])
ax.set_yticklabels(['Male','Female'])
df['A'].hist(ax=ax,orientation='horizontal')
fig.tight_layout()  # Improves appearance a bit.
plt.show()

enter image description here

Upvotes: 0

Views: 3996

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

plt.hist(df['A']) only works by coincidence. I would recommend not to use plt.hist for non-numeric or categorical plots - it's not meant to be used for that.

Also, it's often a good idea to separate data aggregation from visualization. So, using pandas plotting,

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A':['Male'] * 10 + ['Female'] * 5})
df["A"].value_counts().plot.barh()
plt.show()

Or using matplotlib plotting,

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A':['Male'] * 10 + ['Female'] * 5})
counts = df["A"].value_counts()
plt.barh(counts.index, counts)
plt.show()

Upvotes: 4

Related Questions