badavadapav
badavadapav

Reputation: 91

How to add title, x axis label and y axis label while using .subplot in matplotlib?

I have a dateframe called for_plot and I am using the following snippet of code to make a bar diagram:

import matlplotlib.pyplot as plt
f, ax = plt.subplots(1,1,figsize=(10,8))
x_1 = for_plot['res_code'] - 0.2
x_2 = for_plot['res_code']
pre = for_plot['n_indnota_pre']
post = for_plot['n_indnota_post']
ax.bar(x_1,pre, width = 0.2, color = 'red')
ax.bar(x_2,post, width = 0.2, color = 'green')
ax.set_xticks([0.9,1.9,2.9])
ax.set_xticklabels(['GEN','ST','SC'])
ax.legend(['pre_nota', 'post_nota'],loc = 1)

ax.xlabel('Constituency Type')
ax.ylabel('No of Independent Candidates')
ax.title('Average No Of Independent Candidates by Constituency Type')

plt.show()

I do understand how to work around with matplotlib but I have a few questions on the nuances:

  1. What does f in line 1 of the snippet do? As the snippet stands, what do f and ax represent?
  2. I am not able to add the axes labels and chart title (as in the last 4 lines of the snippet) using ax.xlabel('Constituency Type') but while drawing other figures, If I don't call subplot() in the first line and use plt.xlabel('Constituency Type'), it works absolutely fine. Why does it behave this way?

I get the following error:

AttributeError: 'AxesSubplot' object has no attribute 'xlabel'

Edit 1:

f.xlabel('Constituency Type')
f.ylabel('No of Independent Candidates')
f.title('Average No Of Independent Candidates by Constituency Type')

Doesn't work either.

AttributeError:'Figure' object has no attribute 'xlabel'

Upvotes: 1

Views: 2912

Answers (1)

GIRISH kuniyal
GIRISH kuniyal

Reputation: 770

Hope below answer will help.

  1. f represent Figure object which is the top level container for all the plot elements and ax is object or array of Axes objects (in your case its single object)

  2. You can use code below for setting label and title of subplots: ax.set_xlabel('common xlabel') ax.set_ylabel('common ylabel') ax.set_title('ax title')

Upvotes: 2

Related Questions