Related
I need to take an image and save it after some process. The figure looks fine when I display it, but after saving the figure, I got some white space around the saved image. I have tried the 'tight' option for savefig method, did not work either. The code:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax = fig.add_subplot(1, 1, 1)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
I am trying to draw a basic graph by using NetworkX on a figure and save it. I realized that without a graph it works, but when added a graph I get white space around the saved image;
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1, 3)
G.add_edge(1, 2)
pos = {1:[100, 120], 2:[200, 300], 3:[50, 75]}
fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax = fig.add_subplot(1, 1, 1)
nx.draw(G, pos=pos)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
You can remove the white space padding by setting bbox_inches="tight" in savefig:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file.
(Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments.
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
The following function incorporates johannes-s answer above. I have tested it with plt.figure and plt.subplots() with multiple axes, and it works nicely.
def save(filepath, fig=None):
'''Save the current image with no whitespace
Example filepath: "myfig.png" or r"C:\myfig.pdf"
'''
import matplotlib.pyplot as plt
if not fig:
fig = plt.gcf()
plt.subplots_adjust(0,0,1,1,0,0)
for ax in fig.axes:
ax.axis('off')
ax.margins(0,0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
fig.savefig(filepath, pad_inches = 0, bbox_inches='tight')
The most straightforward method is to use plt.tight_layout transformation which is actually more preferable as it doesn't do unnecessary cropping when using plt.savefig
import matplotlib as plt
plt.plot([1,2,3], [1,2,3])
plt.tight_layout(pad=0)
plt.savefig('plot.png')
However, this may not be preferable for complex plots that modifies the figure. Refer to Johannes S's answer that uses plt.subplots_adjust if that's the case.
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
This worked for me
plt.savefig(save_path,bbox_inches='tight', pad_inches=0, transparent=True)
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',
bbox_inches='tight', pad_inches=0, format='pdf', dpi=1200)
A much simpler approach I found is to use plt.imsave :
import matplotlib.pyplot as plt
arr = plt.imread(path)
plt.imsave('test.png', arr)
For anyone who wants to work in pixels rather than inches this will work.
Plus the usual you will also need
from matplotlib.transforms import Bbox
Then you can use the following:
my_dpi = 100 # Good default - doesn't really matter
# Size of output in pixels
h = 224
w = 224
fig, ax = plt.subplots(1, figsize=(w/my_dpi, h/my_dpi), dpi=my_dpi)
ax.set_position([0, 0, 1, 1]) # Critical!
# Do some stuff
ax.imshow(img)
ax.imshow(heatmap) # 4-channel RGBA
ax.plot([50, 100, 150], [50, 100, 150], color="red")
ax.axis("off")
fig.savefig("saved_img.png",
bbox_inches=Bbox([[0, 0], [w/my_dpi, h/my_dpi]]),
dpi=my_dpi)
So the solution depend on whether you adjust the subplot. If you specify plt.subplots_adjust (top, bottom, right, left), you don't want to use the kwargs of bbox_inches='tight' with plt.savefig, as it paradoxically creates whitespace padding. It also allows you to save the image as the same dims as the input image (600x600 input image saves as 600x600 pixel output image).
If you don't care about the output image size consistency, you can omit the plt.subplots_adjust attributes and just use the bbox_inches='tight' and pad_inches=0 kwargs with plt.savefig.
This solution works for matplotlib versions 3.0.1, 3.0.3 and 3.2.1. It also works when you have more than 1 subplot (eg. plt.subplots(2,2,...).
def save_inp_as_output(_img, c_name, dpi=100):
h, w, _ = _img.shape
fig, axes = plt.subplots(figsize=(h/dpi, w/dpi))
fig.subplots_adjust(top=1.0, bottom=0, right=1.0, left=0, hspace=0, wspace=0)
axes.imshow(_img)
axes.axis('off')
plt.savefig(c_name, dpi=dpi, format='jpeg')
You may try this. It solved my issue.
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img, cmap=cmap)
In a Jupyter notebook, one can add this line:
%config InlineBackend.print_figure_kwargs = {'pad_inches':0}
Here is a minimal example
import matplotlib.pyplot as plt
import numpy as np
%config InlineBackend.print_figure_kwargs = {'pad_inches':0}
fig, ax = plt.subplots()
ax.axis("off")
ax.imshow(np.fromfunction(lambda i, j: np.sin(j), (15, 15)), cmap="YlGnBu")
This works for me saving a numpy array plotted with imshow to file
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,10))
plt.imshow(img) # your image here
plt.axis("off")
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.savefig("example2.png", box_inches='tight', dpi=100)
plt.show()
How can I extend the plot area to take up the whole canvas and essentially remove the gray area in the image? I've looked around and I haven't found any solutions, although maybe it's because I don't know what to call that area so searching is challenging.
Using fig.tight_layout() reduces the gray but does not remove it.
from matplotlib import pyplot as plt
y = [1,3,5,6,7,8,12,13,15,15,16,25,26,28,29,36]
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
fig, ax = plt.subplots(figsize=(8,4), dpi=85)
ax.stackplot(x, y, color='w', colors=('#ededed',))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.set_ylim([0,max(y)*1.2])
ax.set_xlim([0,30])
plt.show()
Specify that the Axes take up the whole Figure when you create the Axes --
fig = plt.figure()
ax = fig.add_axes((0,0,1,1), frameon=False)
ax.plot([2,5,4])
now, there's a lot there isn't room for any more, e.g. external tick labels; and Tkinter may be doing some padding itself; but this is as large as you can make an Axes. ( (0,0,1,1) is extent in Figure coordinates.)
I am plotting an image in matplotlib, and it keeps giving me some padding. This is what I have tried:
def field_plot():
x = [i[0] for i in path]
y = [i[1] for i in path]
plt.clf()
plt.axis([0, 560, 0, 820])
im = plt.imread('field.jpg')
field = plt.imshow(im)
for i in range(len(r)):
plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
plt.axis('off')
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
plt.clf()
Try using pad_inches=0, i.e.
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True", pad_inches=0)
From the documentation:
pad_inches: Amount of padding around the figure when bbox_inches is
‘tight’.
I think the default is pad_inches=0.1
Just add plt.tight_layout() before plt.savefig() !!
plt.figure(figsize=(16, 10))
# ... Doing Something ...
plt.tight_layout()
plt.savefig('wethers.png')
plt.show()
This worked for me. After plotting, get the Axes object from plt using ax = plt.gca(). Then set the xlim, and ylim of ax object to match image width and image height. Matplotlib seems to automatically increase xlim and ylim of viewing area when you plot. Note that while setting y_lim you have to invert the order of coordinates.
for i in range(len(r)):
plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
plt.axis('off')
ax = plt.gca();
ax.set_xlim(0.0, width_of_im);
ax.set_ylim(height_of_im, 0.0);
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
All previous approaches didn't quite work for me, they all left some padding around the figure.
The following lines successfully removed the white or transparent padding that was left:
plt.axis('off')
ax = plt.gca()
ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator())
plt.savefig(IMG_DIR + 'match.png', pad_inches=0, bbox_inches='tight', transparent=True)
Use plt.gca().set_position((0, 0, 1, 1)) to let the axes span the whole figure, see reference.
If plt.imshow is used, this requires that the figure has the correct aspect ratio.
import matplotlib as mpl
import matplotlib.pyplot as plt
# set the correct aspect ratio
dpi = mpl.rcParams["figure.dpi"]
plt.figure(figsize=(560/dpi, 820/dpi))
plt.axis('off')
plt.gca().set_position((0, 0, 1, 1))
im = plt.imread('field.jpg')
plt.imshow(im)
plt.savefig("test.png")
plt.close()
I would like to apply colormap to an image, and write the resulting image, without using axes, labels, titles, or anything automatically added by matplotlib. Here is what I did:
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = plt.imshow(data)
fig.set_cmap('hot')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig(outputname)
It successfully removes the axis of the figure, but the figure saved, presents a white padding, and a frame around the actual image.
How can I remove them (at least the white padding)?
The axis('off') method resolves one of the problems more succinctly than separately changing each axis and border. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there; you can see in the example below that the white space left is much smaller, but still present.
Newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via #episodeyang and #kadrach)
from numpy import random
import matplotlib.pyplot as plt
data = random.random((5,5))
img = plt.imshow(data, interpolation='nearest')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')
I learned this trick from matehat, here:
import matplotlib.pyplot as plt
import numpy as np
def make_image(data, outputname, size=(1, 1), dpi=80):
fig = plt.figure()
fig.set_size_inches(size)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
plt.set_cmap('hot')
ax.imshow(data, aspect='equal')
plt.savefig(outputname, dpi=dpi)
# data = mpimg.imread(inputname)[:,:,0]
data = np.arange(1,10).reshape((3, 3))
make_image(data, '/tmp/out.png')
yields
Possible simplest solution:
I simply combined the method described in the question and the method from the answer by Hooked.
fig = plt.imshow(my_data)
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)
After this code there is no whitespaces and no frame.
No one mentioned imsave yet, which makes this a one-liner:
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(10000).reshape((100, 100))
plt.imsave("/tmp/foo.png", data, format="png", cmap="hot")
It directly stores the image as it is, i.e. does not add any axes or border/padding.
plt.axis('off')
plt.savefig('example.png',bbox_inches='tight',pad_inches = 0)
gets me the borderless image.
I found that it is all documented...
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.axis.html#matplotlib.axes.Axes.axis
My code…. "bcK" is a 512x512 image
plt.figure()
plt.imshow(bck)
plt.axis("off") # turns off axes
plt.axis("tight") # gets rid of white border
plt.axis("image") # square up the image instead of filling the "figure" space
plt.show()
This should remove all padding and borders:
from matplotlib import pyplot as plt
fig = plt.figure()
fig.patch.set_visible(False)
ax = fig.add_subplot(111)
plt.axis('off')
plt.imshow(data)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("../images/test.png", bbox_inches=extent)
You can also specify the extent of the figure to the bbox_inches argument. This would get rid of the white padding around the figure.
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = plt.imshow(data)
fig.set_cmap('hot')
ax = fig.gca()
ax.set_axis_off()
ax.autoscale(False)
extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())
plt.savefig(outputname, bbox_inches=extent)
The upvoted answer does not work anymore. To get it to work you need
to manually add an axis set to [0, 0, 1, 1], or remove the patch under figure.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(5, 5), dpi=20)
ax = plt.Axes(fig, [0., 0., 1., 1.])
fig.add_axes(ax)
plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off') # same as: ax.set_axis_off()
plt.savefig("test.png")
Alternatively, you could just remove the patch. You don't need to add a subplot in order to remove the paddings. This is simplified from Vlady's answer below
fig = plt.figure(figsize=(5, 5))
fig.patch.set_visible(False) # turn off the patch
plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off')
plt.savefig("test.png", cmap='hot')
This is tested with version 3.0.3 on 2019/06/19. Image see bellow:
A much simpler thing to do is to use pyplot.imsave. For details, see luator's answer bellow
I liked ubuntu's answer, but it was not showing explicitly how to set the size for non-square images out-of-the-box, so I modified it for easy copy-paste:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
def save_image_fix_dpi(data, dpi=100):
shape=np.shape(data)[0:2][::-1]
size = [float(i)/dpi for i in shape]
fig = plt.figure()
fig.set_size_inches(size)
ax = plt.Axes(fig,[0,0,1,1])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(data)
fig.savefig('out.png', dpi=dpi)
plt.show()
Saving images without border is easy whatever dpi you choose if pixel_size/dpi=size is kept.
data = mpimg.imread('test.png')
save_image_fix_dpi(data, dpi=100)
However displaying is spooky. If you choose small dpi, your image size can be larger than your screen and you get border during display. Nevertheless, this does not affect saving.
So for
save_image_fix_dpi(data, dpi=20)
The display becomes bordered (but saving works):
This is what finally worked for me:
ax.margins(x=0, y=0, tight=True) was the key line.
fig = plt.figure(figsize=(8, 8))
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
ax.margins(x=0, y=0, tight=True)
fig.add_axes(ax)
for triangle in list_of_triangles:
x_points = [point[0] for point in triangle]
y_points = [point[1] for point in triangle]
plt.fill(x_points, y_points, 'k', edgecolor='k')
plt.savefig("test.png", bbox_inches=0, pad_inches=0)
plt.show()
First, for certain image formats (i.e. TIFF) you can actually save the colormap in the header and most viewers will show your data with the colormap.
For saving an actual matplotlib image, which can be useful for adding annotations or other data to images, I've used the following solution:
fig, ax = plt.subplots(figsize=inches)
ax.matshow(data) # or you can use also imshow
# add annotations or anything else
# The code below essentially moves your plot so that the upper
# left hand corner coincides with the upper left hand corner
# of the artist
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# now generate a Bbox instance that is the same size as your
# single axis size (this bbox will only encompass your figure)
bbox = matplotlib.transforms.Bbox(((0, 0), inches))
# now you can save only the part of the figure with data
fig.savefig(savename, bbox_inches=bbox, **kwargs)
Thanks for the awesome answers from everyone ...I had exactly the same problem with wanting to plot just an image with no extra padding/space etc, so was super happy to find everyone's ideas here.
Apart from image with no padding, I also wanted to be able to easily add annotations etc, beyond just a simple image plot.
So what I ended up doing was combining David's answer with csnemes' to make a simple wrapper at the figure creation time. When you use that, you don't need any changes later with imsave() or anything else:
def get_img_figure(image, dpi):
"""
Create a matplotlib (figure,axes) for an image (numpy array) setup so that
a) axes will span the entire figure (when saved no whitespace)
b) when saved the figure will have the same x/y resolution as the array,
with the dpi value you pass in.
Arguments:
image -- numpy 2d array
dpi -- dpi value that the figure should use
Returns: (figure, ax) tuple from plt.subplots
"""
# get required figure size in inches (reversed row/column order)
inches = image.shape[1]/dpi, image.shape[0]/dpi
# make figure with that size and a single axes
fig, ax = plt.subplots(figsize=inches, dpi=dpi)
# move axes to span entire figure area
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
return fig, ax
I have been looking for several codes to solve this problem and the verified answer to this question is the only code that helped me.
This is useful for scatter plots and triplots. All you have to do is change the margins to zero and you are all done.
This works:
plot.axis('off')
ax = plot.gca()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
This worked for me to remove the ticks:
fig, axes = plt.subplots(2, figsize=(15, 20))
for ax in axes:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
I tried
plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.bottom'] = False
plt.rcParams['ytick.major.left'] = False
plt.rcParams['ytick.major.right'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams['xtick.major.top'] = False
plt.rcParams['xtick.major.bottom'] = False
plt.rcParams['xtick.minor.top'] = False
plt.rcParams['xtick.minor.bottom'] = False
fig = plt.figure()
And it removes all border and axes.
I get this from another question on Stack Overflow.
Define data
x = np.linspace(0,2*np.pi,100)
y = 2*np.sin(x)
Plot
fig = plt.figure()
ax = plt.axes()
fig.add_subplot(ax)
ax.plot(x,y)
Add second axis
newax = plt.axes(axisbg='none')
Gives me ValueError: Unknown element o, even though it does the same thing as what I am about to describe. I can also see that this works (no error) to do the same thing:
newax = plt.axes()
fig.add_subplot(newax)
newax.set_axis_bgcolor('none')
However, it turns the background color of the original figure "gray" (or whatever the figure background is)? I don't understand, as I thought this would make newax transparent except for the axes and box around the figure. Even if I switch the order, same thing:
plt.close('all')
fig = plt.figure()
newax = plt.axes()
fig.add_subplot(newax)
newax.set_axis_bgcolor('none')
ax = plt.axes()
fig.add_subplot(ax)
ax.plot(x,y)
This is surprising because I thought the background of one would be overlaid on the other, but in either case it is the newax background that appears to be visible (or at least this is the color I see).
What is going on here?
You're not actually adding a new axes.
Matplotlib is detecting that there's already a plot in that position and returning it instead of a new axes object.
(Check it for yourself. ax and newax will be the same object.)
There's probably not a reason why you'd want to, but here's how you'd do it.
(Also, don't call newax = plt.axes() and then call fig.add_subplot(newax) You're doing the same thing twice.)
Edit: With newer (>=1.2, I think?) versions of matplotlib, you can accomplish the same thing as the example below by using the label kwarg to fig.add_subplot. E.g. newax = fig.add_subplot(111, label='some unique string')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
# If you just call `plt.axes()` or equivalently `fig.add_subplot()` matplotlib
# will just return `ax` again. It _won't_ create a new axis unless we
# call fig.add_axes() or reset fig._seen
newax = fig.add_axes(ax.get_position(), frameon=False)
ax.plot(range(10), 'r-')
newax.plot(range(50), 'g-')
newax.axis('equal')
plt.show()
Of course, this looks awful, but it's what you're asking for...
I'm guessing from your earlier questions that you just want to add a second x-axis? If so, this is a completely different thing.
If you want the y-axes linked, then do something like this (somewhat verbose...):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
newax = ax.twiny()
# Make some room at the bottom
fig.subplots_adjust(bottom=0.20)
# I'm guessing you want them both on the bottom...
newax.set_frame_on(True)
newax.patch.set_visible(False)
newax.xaxis.set_ticks_position('bottom')
newax.xaxis.set_label_position('bottom')
newax.spines['bottom'].set_position(('outward', 40))
ax.plot(range(10), 'r-')
newax.plot(range(21), 'g-')
ax.set_xlabel('Red Thing')
newax.set_xlabel('Green Thing')
plt.show()
If you want to have a hidden, unlinked y-axis, and an entirely new x-axis, then you'd do something like this:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
newax = fig.add_axes(ax.get_position())
newax.patch.set_visible(False)
newax.yaxis.set_visible(False)
for spinename, spine in newax.spines.iteritems():
if spinename != 'bottom':
spine.set_visible(False)
newax.spines['bottom'].set_position(('outward', 25))
ax.plot(range(10), 'r-')
x = np.linspace(0, 6*np.pi)
newax.plot(x, 0.001 * np.cos(x), 'g-')
plt.show()
Note that the y-axis values for anything plotted on newax are never shown.
If you wanted, you could even take this one step further, and have independent x and y axes (I'm not quite sure what the point of it would be, but it looks neat...):
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2, right=0.85)
newax = fig.add_axes(ax.get_position())
newax.patch.set_visible(False)
newax.yaxis.set_label_position('right')
newax.yaxis.set_ticks_position('right')
newax.spines['bottom'].set_position(('outward', 35))
ax.plot(range(10), 'r-')
ax.set_xlabel('Red X-axis', color='red')
ax.set_ylabel('Red Y-axis', color='red')
x = np.linspace(0, 6*np.pi)
newax.plot(x, 0.001 * np.cos(x), 'g-')
newax.set_xlabel('Green X-axis', color='green')
newax.set_ylabel('Green Y-axis', color='green')
plt.show()
You can also just add an extra spine at the bottom of the plot. Sometimes this is easier, especially if you don't want ticks or numerical things along it. Not to plug one of my own answers too much, but there's an example of that here: How do I plot multiple X or Y axes in matplotlib?
As one last thing, be sure to look at the parasite axes examples if you want to have the different x and y axes linked through a specific transformation.