Resize a figure automatically in matplotlib










30















Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?



I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.



I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?










share|improve this question


























    30















    Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?



    I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.



    I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?










    share|improve this question
























      30












      30








      30


      9






      Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?



      I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.



      I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?










      share|improve this question














      Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?



      I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.



      I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?







      python matplotlib






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 13 '09 at 9:38









      pufferfishpufferfish

      7,353134758




      7,353134758






















          6 Answers
          6






          active

          oldest

          votes


















          40














          Use bbox_inches='tight'



          import numpy as np
          import matplotlib.pyplot as plt
          import matplotlib.cm as cm

          X = 10*np.random.rand(5,3)

          fig = plt.figure(figsize=(15,5),facecolor='w')
          ax = fig.add_subplot(111)
          ax.imshow(X, cmap=cm.jet)

          plt.savefig("image.png",bbox_inches='tight',dpi=100)


          ...only works when saving images though, not showing them.






          share|improve this answer


















          • 1





            What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

            – dangerous
            Mar 3 '15 at 6:27



















          13














          just use aspect='auto' when you call imshow



          import numpy as np
          import matplotlib.pyplot as plt
          import matplotlib.cm as cm

          X = 10*np.random.rand(5,3)
          plt.imshow(X, aspect='auto')


          it works even if it is just for showing and not saving






          share|improve this answer

























          • @pufferfish this answer is better than the other one, as it works for showing and saving

            – Homero Barrocas S Esmeraldo
            Aug 2 '18 at 12:50


















          7














          Another way of doing this is using the matplotlib tight_layout function



          import matplotlib.pyplot as plt
          fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
          data = [0,1,2,3,4]
          ax.plot(data)
          fig.tight_layout()
          fig.show()





          share|improve this answer






























            3














            Do you mean changing the size of the image or the area that is visable within a plot?



            The size of a figure can be set with Figure.set_figsize_inches.
            Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.



            Also take a look at this question.






            share|improve this answer

























            • I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

              – pufferfish
              Aug 13 '09 at 10:35











            • I think the correct command is .set_size_inches without the fig

              – innisfree
              Nov 17 '13 at 22:20



















            2














            you can try using axis('scaled')



            import matplotlib.pyplot as plt
            import numpy

            #some dummy images
            img1 = numpy.array([[.1,.2],[.3,.4]])
            img2 = numpy.array([[.1,.2],[.3,.4]])

            fig,ax = plt.subplots()
            ax.imshow(img1,extent=[0,1,0,1])
            ax.imshow(img2,extent=[2,3,0,1])
            ax.axis('scaled') #this line fits your images to screen
            plt.show()





            share|improve this answer






























              0














              Also possible to use ax.autoscale with ax object



              ax.autoscale(enable=True) 





              share|improve this answer
























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1271023%2fresize-a-figure-automatically-in-matplotlib%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                40














                Use bbox_inches='tight'



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)

                fig = plt.figure(figsize=(15,5),facecolor='w')
                ax = fig.add_subplot(111)
                ax.imshow(X, cmap=cm.jet)

                plt.savefig("image.png",bbox_inches='tight',dpi=100)


                ...only works when saving images though, not showing them.






                share|improve this answer


















                • 1





                  What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                  – dangerous
                  Mar 3 '15 at 6:27
















                40














                Use bbox_inches='tight'



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)

                fig = plt.figure(figsize=(15,5),facecolor='w')
                ax = fig.add_subplot(111)
                ax.imshow(X, cmap=cm.jet)

                plt.savefig("image.png",bbox_inches='tight',dpi=100)


                ...only works when saving images though, not showing them.






                share|improve this answer


















                • 1





                  What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                  – dangerous
                  Mar 3 '15 at 6:27














                40












                40








                40







                Use bbox_inches='tight'



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)

                fig = plt.figure(figsize=(15,5),facecolor='w')
                ax = fig.add_subplot(111)
                ax.imshow(X, cmap=cm.jet)

                plt.savefig("image.png",bbox_inches='tight',dpi=100)


                ...only works when saving images though, not showing them.






                share|improve this answer













                Use bbox_inches='tight'



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)

                fig = plt.figure(figsize=(15,5),facecolor='w')
                ax = fig.add_subplot(111)
                ax.imshow(X, cmap=cm.jet)

                plt.savefig("image.png",bbox_inches='tight',dpi=100)


                ...only works when saving images though, not showing them.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 14 '09 at 15:57









                pufferfishpufferfish

                7,353134758




                7,353134758







                • 1





                  What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                  – dangerous
                  Mar 3 '15 at 6:27













                • 1





                  What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                  – dangerous
                  Mar 3 '15 at 6:27








                1




                1





                What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                – dangerous
                Mar 3 '15 at 6:27






                What does that fig.add_subplot(111) indicate? I mean the number within the square brackets ((111))

                – dangerous
                Mar 3 '15 at 6:27














                13














                just use aspect='auto' when you call imshow



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)
                plt.imshow(X, aspect='auto')


                it works even if it is just for showing and not saving






                share|improve this answer

























                • @pufferfish this answer is better than the other one, as it works for showing and saving

                  – Homero Barrocas S Esmeraldo
                  Aug 2 '18 at 12:50















                13














                just use aspect='auto' when you call imshow



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)
                plt.imshow(X, aspect='auto')


                it works even if it is just for showing and not saving






                share|improve this answer

























                • @pufferfish this answer is better than the other one, as it works for showing and saving

                  – Homero Barrocas S Esmeraldo
                  Aug 2 '18 at 12:50













                13












                13








                13







                just use aspect='auto' when you call imshow



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)
                plt.imshow(X, aspect='auto')


                it works even if it is just for showing and not saving






                share|improve this answer















                just use aspect='auto' when you call imshow



                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.cm as cm

                X = 10*np.random.rand(5,3)
                plt.imshow(X, aspect='auto')


                it works even if it is just for showing and not saving







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jul 8 '13 at 3:49

























                answered May 4 '12 at 11:51









                Homero Barrocas S EsmeraldoHomero Barrocas S Esmeraldo

                186114




                186114












                • @pufferfish this answer is better than the other one, as it works for showing and saving

                  – Homero Barrocas S Esmeraldo
                  Aug 2 '18 at 12:50

















                • @pufferfish this answer is better than the other one, as it works for showing and saving

                  – Homero Barrocas S Esmeraldo
                  Aug 2 '18 at 12:50
















                @pufferfish this answer is better than the other one, as it works for showing and saving

                – Homero Barrocas S Esmeraldo
                Aug 2 '18 at 12:50





                @pufferfish this answer is better than the other one, as it works for showing and saving

                – Homero Barrocas S Esmeraldo
                Aug 2 '18 at 12:50











                7














                Another way of doing this is using the matplotlib tight_layout function



                import matplotlib.pyplot as plt
                fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
                data = [0,1,2,3,4]
                ax.plot(data)
                fig.tight_layout()
                fig.show()





                share|improve this answer



























                  7














                  Another way of doing this is using the matplotlib tight_layout function



                  import matplotlib.pyplot as plt
                  fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
                  data = [0,1,2,3,4]
                  ax.plot(data)
                  fig.tight_layout()
                  fig.show()





                  share|improve this answer

























                    7












                    7








                    7







                    Another way of doing this is using the matplotlib tight_layout function



                    import matplotlib.pyplot as plt
                    fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
                    data = [0,1,2,3,4]
                    ax.plot(data)
                    fig.tight_layout()
                    fig.show()





                    share|improve this answer













                    Another way of doing this is using the matplotlib tight_layout function



                    import matplotlib.pyplot as plt
                    fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
                    data = [0,1,2,3,4]
                    ax.plot(data)
                    fig.tight_layout()
                    fig.show()






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 26 '16 at 15:38









                    Simon HobbsSimon Hobbs

                    49747




                    49747





















                        3














                        Do you mean changing the size of the image or the area that is visable within a plot?



                        The size of a figure can be set with Figure.set_figsize_inches.
                        Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.



                        Also take a look at this question.






                        share|improve this answer

























                        • I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                          – pufferfish
                          Aug 13 '09 at 10:35











                        • I think the correct command is .set_size_inches without the fig

                          – innisfree
                          Nov 17 '13 at 22:20
















                        3














                        Do you mean changing the size of the image or the area that is visable within a plot?



                        The size of a figure can be set with Figure.set_figsize_inches.
                        Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.



                        Also take a look at this question.






                        share|improve this answer

























                        • I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                          – pufferfish
                          Aug 13 '09 at 10:35











                        • I think the correct command is .set_size_inches without the fig

                          – innisfree
                          Nov 17 '13 at 22:20














                        3












                        3








                        3







                        Do you mean changing the size of the image or the area that is visable within a plot?



                        The size of a figure can be set with Figure.set_figsize_inches.
                        Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.



                        Also take a look at this question.






                        share|improve this answer















                        Do you mean changing the size of the image or the area that is visable within a plot?



                        The size of a figure can be set with Figure.set_figsize_inches.
                        Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.



                        Also take a look at this question.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited May 23 '17 at 12:10









                        Community

                        11




                        11










                        answered Aug 13 '09 at 10:31









                        wierobwierob

                        3,47812024




                        3,47812024












                        • I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                          – pufferfish
                          Aug 13 '09 at 10:35











                        • I think the correct command is .set_size_inches without the fig

                          – innisfree
                          Nov 17 '13 at 22:20


















                        • I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                          – pufferfish
                          Aug 13 '09 at 10:35











                        • I think the correct command is .set_size_inches without the fig

                          – innisfree
                          Nov 17 '13 at 22:20

















                        I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                        – pufferfish
                        Aug 13 '09 at 10:35





                        I mean the dimensions of the Figure object. i.e. Crop the figure to fit the contained plot(s). One would probably have to provide either a width or a height first, and have the other calculated.

                        – pufferfish
                        Aug 13 '09 at 10:35













                        I think the correct command is .set_size_inches without the fig

                        – innisfree
                        Nov 17 '13 at 22:20






                        I think the correct command is .set_size_inches without the fig

                        – innisfree
                        Nov 17 '13 at 22:20












                        2














                        you can try using axis('scaled')



                        import matplotlib.pyplot as plt
                        import numpy

                        #some dummy images
                        img1 = numpy.array([[.1,.2],[.3,.4]])
                        img2 = numpy.array([[.1,.2],[.3,.4]])

                        fig,ax = plt.subplots()
                        ax.imshow(img1,extent=[0,1,0,1])
                        ax.imshow(img2,extent=[2,3,0,1])
                        ax.axis('scaled') #this line fits your images to screen
                        plt.show()





                        share|improve this answer



























                          2














                          you can try using axis('scaled')



                          import matplotlib.pyplot as plt
                          import numpy

                          #some dummy images
                          img1 = numpy.array([[.1,.2],[.3,.4]])
                          img2 = numpy.array([[.1,.2],[.3,.4]])

                          fig,ax = plt.subplots()
                          ax.imshow(img1,extent=[0,1,0,1])
                          ax.imshow(img2,extent=[2,3,0,1])
                          ax.axis('scaled') #this line fits your images to screen
                          plt.show()





                          share|improve this answer

























                            2












                            2








                            2







                            you can try using axis('scaled')



                            import matplotlib.pyplot as plt
                            import numpy

                            #some dummy images
                            img1 = numpy.array([[.1,.2],[.3,.4]])
                            img2 = numpy.array([[.1,.2],[.3,.4]])

                            fig,ax = plt.subplots()
                            ax.imshow(img1,extent=[0,1,0,1])
                            ax.imshow(img2,extent=[2,3,0,1])
                            ax.axis('scaled') #this line fits your images to screen
                            plt.show()





                            share|improve this answer













                            you can try using axis('scaled')



                            import matplotlib.pyplot as plt
                            import numpy

                            #some dummy images
                            img1 = numpy.array([[.1,.2],[.3,.4]])
                            img2 = numpy.array([[.1,.2],[.3,.4]])

                            fig,ax = plt.subplots()
                            ax.imshow(img1,extent=[0,1,0,1])
                            ax.imshow(img2,extent=[2,3,0,1])
                            ax.axis('scaled') #this line fits your images to screen
                            plt.show()






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 '18 at 21:19









                            jelde015jelde015

                            18815




                            18815





















                                0














                                Also possible to use ax.autoscale with ax object



                                ax.autoscale(enable=True) 





                                share|improve this answer





























                                  0














                                  Also possible to use ax.autoscale with ax object



                                  ax.autoscale(enable=True) 





                                  share|improve this answer



























                                    0












                                    0








                                    0







                                    Also possible to use ax.autoscale with ax object



                                    ax.autoscale(enable=True) 





                                    share|improve this answer















                                    Also possible to use ax.autoscale with ax object



                                    ax.autoscale(enable=True) 






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 2 at 13:14









                                    Andrew D.

                                    8761023




                                    8761023










                                    answered Jan 30 at 2:35









                                    ShakujinShakujin

                                    268




                                    268



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1271023%2fresize-a-figure-automatically-in-matplotlib%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        這個網誌中的熱門文章

                                        What does pagestruct do in Eviews?

                                        Dutch intervention in Lombok and Karangasem

                                        Channel Islands