Martin
Martin

Reputation: 41

Add grid and change size in barh python

I am using matplotlib to draw horizontal plots. I want to add grids and change size of the plot to avoid overleap of the label. My code looks like this:

baseline = [0.5745,0.5282,0.4923,0.5077,0.5487,0.5385,0.5231]
low = [0.2653,0.3878,0.3673,0.5510,0.2245,0.5714,0.3265]
high = [0.5102,0.5102,0.3673,0.3877,0.5306,0.4286,0.49]
index = ['Bagging','Decision tree','Gussian Naive Bayes','Logistic regression','Random forest','SVM','k-NN']
df = pd.DataFrame({'Baseline': baseline,'ttd lower than median': low,'ttd higher than median': high}, index=index)
plt.figure(figsize = (6,12))
ax.yaxis.grid(color='gray', linestyle='dashed')
ax = df.plot.barh()

and the resulting plot looks like this:

enter image description here

However, it didn't show the grid and "plt.figure(figsize = (6,12))" seems did not work. How can I fix this? Thanks in advance!

Upvotes: 0

Views: 407

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62463

  • Specify the location of the legend by using plt.legend
    • Making the figure larger won't necessarily make the legend fit better
  • Show the grid by using plt.grid()
  • plt.figure(figsize = (6,12)) didn't work, because the dataframe plot wasn't using this axes.
fig, ax = plt.subplots(figsize=(7, 12))
ax.yaxis.grid(color='gray', linestyle='dashed')
df.plot.barh(ax=ax)  # ax=ax lets the dataframe plot use the subplot axes
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')  # place the legend outside
plt.grid()  # show the grid

enter image description here

  • Alternatively, use df.plot.barh(ax=ax, figsize=(7, 12))
p = df.plot.barh(figsize=(7, 8))
p.yaxis.grid(color='gray', linestyle='dashed')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

enter image description here

Upvotes: 1

Related Questions