0

I am trying to set the x and y limits on a subplot but am having difficultly. I suspect that the difficultly stems from my fundamental lack of understanding of how figures and subplots work. I have read these two questions:

question 1

question 2

I tried to use that approach, but neither had any effect on the x and y limits. Here's my code:

fig = plt.figure(figsize=(9,6))
ax = plt.subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
ax.set_ylim=([0,200])
ax.set_xlim=([0,100])
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()

I am confused as whether to apply commands to fig or ax? For instance .xlabel and .title don't seem to be available for ax. Thanks

Community
  • 1
  • 1
TaxpayersMoney
  • 669
  • 1
  • 8
  • 26

3 Answers3

0

Why don't you do: Ax = fig.add_subplot(111)

import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(100)

fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111)
ax.hist(x, bins=30, color='r', alpha=0.3)
ax.set_ylim=(0, 200)
ax.set_xlim=(0, 100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()

I've run your code on some sample code, and I'm attaching the screenshot. I'm not sure this is the desired result but this is what I got.enter image description here

fredstban
  • 66
  • 6
0

For a multiplot, where you have subplots in a single figure, you can have several xlabel and one title

fig.title("foobar")
ax.set_xlabel("x")

This is explained in great detail here on the Matplotlib website.

You in your case, use a subplot for just a single plot. This is possible, just doesn't make a lot of sense. Plots like the one below are supposed to be created with the subplot feature:

enter image description here

To answer your question: you can set the x- and y-limits on a per-subplot and per-axis basis by simply addressing the respective subplot directly (ax for subplot 1) and them calling the set_xlabel member function to set the label on the x-axis.

EDIT

For your updated question:

Use this code as inspiration, I had to generate some data on my own so no guarantees:

import matplotlib.pyplot as plt

plt.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
plt.ylim(0,200)
plt.xlim(0,100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
jhoepken
  • 1,842
  • 3
  • 17
  • 24
  • Removed reference to subplots. Now just use plt,hst. Still not having any luck changing the x and y limits. Also tried doing: fig=plt.figure() but then got an error when trying to do fig.hist(...) 'Figure' has no attribute hist. – TaxpayersMoney Mar 07 '16 at 12:43
0

Bit more googling and I got the following that has worked:

sub_dict = subset(data_dict, 'b', 'a', greater_than, 10)
fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
plt.ylim(0,250)
plt.xlim(0,100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
TaxpayersMoney
  • 669
  • 1
  • 8
  • 26