From saketkc at gmail.com Sun Mar 5 19:02:15 2017 From: saketkc at gmail.com (Saket Choudhary) Date: Sun, 5 Mar 2017 16:02:15 -0800 Subject: [Matplotlib-users] [X-Stackoverflow] Sequence logos using matplotlib: transforming xticks Message-ID: I asked this question on stackoverflow and thought it would make sense to post it here as well: http://stackoverflow.com/questions/42615527/matplotlib-scaled-text-and-xticks Thanks, Saket -------------- next part -------------- An HTML attachment was scrubbed... URL: From jean-philippe.grivet at wanadoo.fr Wed Mar 8 09:19:33 2017 From: jean-philippe.grivet at wanadoo.fr (Jean-Philippe Grivet) Date: Wed, 8 Mar 2017 15:19:33 +0100 Subject: [Matplotlib-users] physical size of plot In-Reply-To: References: Message-ID: <31d14d14-eef0-95ea-d7f8-3783bb85a430@wanadoo.fr> Hello, I use python(3.6)+numpy+matplotlib(2.0) (Anaconda distribution under Win7) to draw simple figures and I meet the following problem. All the figures that I plot come out the same size (432x288 px). This is OK for simple curves but leads to obscure plots in more complicated cases. I notice that all figures in the pyplot tutorial have size 550x450 as they do also in the Matplotlib examples, while many figures in the gallery are 165x135. How canI force the size of a picture in order to display it full screen or to cover most of anA4 sheet of paper ? Thank you for your help JP Grivet --- L'absence de virus dans ce courrier ?lectronique a ?t? v?rifi?e par le logiciel antivirus Avast. https://www.avast.com/antivirus From vincent.adrien at gmail.com Wed Mar 8 10:15:44 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Wed, 8 Mar 2017 16:15:44 +0100 Subject: [Matplotlib-users] physical size of plot In-Reply-To: <31d14d14-eef0-95ea-d7f8-3783bb85a430@wanadoo.fr> References: <31d14d14-eef0-95ea-d7f8-3783bb85a430@wanadoo.fr> Message-ID: <58C02020.60907@gmail.com> Hello Jean-Philippe, you can use the `figsize` keyword argument when creating a figure to set its size in inches (1 in = 2.54 cm). You can also set the DPI value directly with the `dpi` argument. Or you can wait until saving the figure: the keyword argument is the same. For example ```python import matplotlib.pyplot as plt # Set the dimensions that you want in inches, # here let's say a quarter of a A4 sheet. a4_sheet = (21.0, 29.7) # in cm my_size = [0.5*val/2.54 for val in a4_sheet] # converted in inches fig, ax = plt.subplots(figsize=my_size) # one could add 'dpi=300' ax.plot([0, 1, 2], [1, 2, 0]) # dummy plot # Saving with a specific dot-per-inch (dpi) value, here 300 # Given my_size, the final picture should be ~ 1240x1754 fig.savefig('my_figure_in_300_dpi.png', dpi=300) ``` You may find more details in the online documentation: - [pyplot.figure](http://matplotlib.org/api/pyplot_api.html?highlight=figure#matplotlib.pyplot.figure) - [pyplot.savefig](http://matplotlib.org/api/pyplot_api.html?highlight=savefig#matplotlib.pyplot.savefig) I hope this helps. Regards Adrien PS: the figure size that you report is a bit surprising. The 2.0 defaults are expected to produce 640?480 pixel-pictures (if I am not wrong). On 08/03/2017 15:19, Jean-Philippe Grivet wrote: > Hello, > > I use python(3.6)+numpy+matplotlib(2.0) (Anaconda distribution under > Win7) to draw simple figures and I meet the following problem. All the > figures that I plot come out the same size (432x288 px). This is OK for > simple curves but leads to obscure plots in more complicated cases. > I notice that all figures in the pyplot tutorial have size 550x450 as > they do also in the Matplotlib examples, while many figures in the > gallery are 165x135. > > How canI force the size of a picture in order to display it full screen > or to cover most of anA4 sheet of paper ? > > Thank you for your help > JP Grivet > > > --- > L'absence de virus dans ce courrier ?lectronique a ?t? v?rifi?e par le > logiciel antivirus Avast. > https://www.avast.com/antivirus > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users From ben.v.root at gmail.com Wed Mar 8 11:34:01 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Wed, 8 Mar 2017 11:34:01 -0500 Subject: [Matplotlib-users] physical size of plot In-Reply-To: <58C02020.60907@gmail.com> References: <31d14d14-eef0-95ea-d7f8-3783bb85a430@wanadoo.fr> <58C02020.60907@gmail.com> Message-ID: The figures in the gallery and documentation might also be automatically cropped to eliminate white space. On Wed, Mar 8, 2017 at 10:15 AM, vincent.adrien at gmail.com < vincent.adrien at gmail.com> wrote: > Hello Jean-Philippe, > > you can use the `figsize` keyword argument when creating a figure to set > its size in inches (1 in = 2.54 cm). You can also set the DPI value > directly with the `dpi` argument. Or you can wait until saving the > figure: the keyword argument is the same. > > For example > ```python > > import matplotlib.pyplot as plt > > # Set the dimensions that you want in inches, > # here let's say a quarter of a A4 sheet. > a4_sheet = (21.0, 29.7) # in cm > my_size = [0.5*val/2.54 for val in a4_sheet] # converted in inches > > fig, ax = plt.subplots(figsize=my_size) # one could add 'dpi=300' > > ax.plot([0, 1, 2], [1, 2, 0]) # dummy plot > > # Saving with a specific dot-per-inch (dpi) value, here 300 > # Given my_size, the final picture should be ~ 1240x1754 > fig.savefig('my_figure_in_300_dpi.png', dpi=300) > > ``` > > You may find more details in the online documentation: > - > [pyplot.figure](http://matplotlib.org/api/pyplot_api. > html?highlight=figure#matplotlib.pyplot.figure) > - > [pyplot.savefig](http://matplotlib.org/api/pyplot_api. > html?highlight=savefig#matplotlib.pyplot.savefig) > > I hope this helps. > > Regards > > Adrien > > PS: the figure size that you report is a bit surprising. The 2.0 > defaults are expected to produce 640?480 pixel-pictures (if I am not > wrong). > > On 08/03/2017 15:19, Jean-Philippe Grivet wrote: > > Hello, > > > > I use python(3.6)+numpy+matplotlib(2.0) (Anaconda distribution under > > Win7) to draw simple figures and I meet the following problem. All the > > figures that I plot come out the same size (432x288 px). This is OK for > > simple curves but leads to obscure plots in more complicated cases. > > I notice that all figures in the pyplot tutorial have size 550x450 as > > they do also in the Matplotlib examples, while many figures in the > > gallery are 165x135. > > > > How canI force the size of a picture in order to display it full screen > > or to cover most of anA4 sheet of paper ? > > > > Thank you for your help > > JP Grivet > > > > > > --- > > L'absence de virus dans ce courrier ?lectronique a ?t? v?rifi?e par le > > logiciel antivirus Avast. > > https://www.avast.com/antivirus > > > > _______________________________________________ > > Matplotlib-users mailing list > > Matplotlib-users at python.org > > https://mail.python.org/mailman/listinfo/matplotlib-users > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jean-philippe.grivet at wanadoo.fr Sat Mar 11 12:54:27 2017 From: jean-philippe.grivet at wanadoo.fr (Jean-Philippe GRIVET) Date: Sat, 11 Mar 2017 18:54:27 +0100 (CET) Subject: [Matplotlib-users] axes properties Message-ID: <466328615.7894.1489254867743.JavaMail.www@wwinf1k15> Hello, I have two questions related to axes in a 3-D plot. 1. I often find that ticks are too close together so that labels overlap.? How can I change the number of ticks or the step length ? 2. The default axes lay-out has x increasing from left to right and y increasing from front to back. My finction decrease quickly with increasing y, so that the corresponding parts of the surface are hidden. Therefore, I would like to have y values increasing from back to front. I understand that yaxis_invert can do it but how is it used ? Thank you for your help Jean-Philippe -------------- next part -------------- An HTML attachment was scrubbed... URL: From amit at phpandmore.net Tue Mar 14 11:43:06 2017 From: amit at phpandmore.net (Amit Yaron) Date: Tue, 14 Mar 2017 17:43:06 +0200 Subject: [Matplotlib-users] axes properties In-Reply-To: <466328615.7894.1489254867743.JavaMail.www@wwinf1k15> References: <466328615.7894.1489254867743.JavaMail.www@wwinf1k15> Message-ID: <58C80F8A.1080800@phpandmore.net> Try using the methods 'set_xticks', 'set_yticks' and 'set_zticks' of the Axes object. Each of them accepts a list of values that will be displayed. For example: ax.set_xticks(np.r_[-10:10:3j]) Will display ticks for values -10,0 and 10 only. On 11/03/17 19:54, Jean-Philippe GRIVET wrote: > Hello, > > I have two questions related to axes in a 3-D plot. > > 1. I often find that ticks are too close together so that labels > overlap. How > can I change the number of ticks or the step length ? > > 2. The default axes lay-out has x increasing from left to right and y > increasing > from front to back. My finction decrease quickly with increasing y, so > that the > corresponding parts of the surface are hidden. Therefore, I would like > to have > y values increasing from back to front. I understand that yaxis_invert > can do it > but how is it used ? > > Thank you for your help > Jean-Philippe > > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > From vincent.adrien at gmail.com Wed Mar 15 05:45:49 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Wed, 15 Mar 2017 10:45:49 +0100 Subject: [Matplotlib-users] axes properties In-Reply-To: <58C80F8A.1080800@phpandmore.net> References: <466328615.7894.1489254867743.JavaMail.www@wwinf1k15> <58C80F8A.1080800@phpandmore.net> Message-ID: <58C90D4D.4050803@gmail.com> Hello Jean-Philippe, To complete Amit's reply and in case nobody else already answered your other question, you can have a look at the following example (the output is attached as a PDF) that shows: - How to define tick locators, which can be useful for example when you do not know in advance what exact values the ticks should have. Please find more informations in the [official docs](http://matplotlib.org/api/ticker_api.html). You may also find of interest these recent examples, about: * [tick locators](http://matplotlib.org/examples/ticks_and_spines/tick-locators.html); * [tick formatters](matplotlib.org/examples/ticks_and_spines/tick-formatters.html); - How to invert one of the axes (the z-axis in the example). ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import (LinearLocator, MaxNLocator, MultipleLocator) def dummy_plot(ax): X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25)) Z = np.sin(np.sqrt(X**2 + Y**2)) ax.plot_surface(X, Y, Z, cmap='coolwarm') return ax fig = plt.figure("Demo_Jean-Philippe_GRIVET", figsize=(4.8 * 3, 4.8)) ax0 = fig.add_subplot(1, 3, 1, projection='3d') ax0 = dummy_plot(ax0) ax0.set_title('Vanilla plot') ax1 = fig.add_subplot(1, 3, 2, projection='3d') ax1 = dummy_plot(ax1) ax1.set_title('Custom locators') ax1.set_xlabel('LinearLocator') # evenly spaced ticks from min to max ax1.xaxis.set_major_locator(LinearLocator(numticks=5)) ax1.set_ylabel('MaxNLocator') # use up to nbins+1 ticks at nice locs ax1.yaxis.set_major_locator(MaxNLocator(nbins=5, symmetric=True, integer=True)) ax1.set_zlabel('MultipleLocator') # ticks/range are a multiple of base ax1.zaxis.set_major_locator(MultipleLocator(base=0.4)) ax2 = fig.add_subplot(1, 3, 3, projection='3d') ax2 = dummy_plot(ax2) ax2.set_title('Inverted z-axis') ax2.invert_zaxis() # From looking at the code, it is equivalent to: # bottom, top = ax2.get_zlim() # ax2.set_zlim(top, bottom, auto=None) plt.tight_layout() plt.show() ``` Best, Adrien On 14/03/2017 16:43, Amit Yaron wrote: > Try using the methods 'set_xticks', 'set_yticks' and 'set_zticks' of the > Axes object. > Each of them accepts a list of values that will be displayed. > For example: > ax.set_xticks(np.r_[-10:10:3j]) > > Will display ticks for values -10,0 and 10 only. > > > On 11/03/17 19:54, Jean-Philippe GRIVET wrote: >> Hello, >> >> I have two questions related to axes in a 3-D plot. >> >> 1. I often find that ticks are too close together so that labels >> overlap. How >> can I change the number of ticks or the step length ? >> >> 2. The default axes lay-out has x increasing from left to right and y >> increasing >> from front to back. My finction decrease quickly with increasing y, so >> that the >> corresponding parts of the surface are hidden. Therefore, I would like >> to have >> y values increasing from back to front. I understand that yaxis_invert >> can do it >> but how is it used ? >> >> Thank you for your help >> Jean-Philippe >> >> >> >> _______________________________________________ >> Matplotlib-users mailing list >> Matplotlib-users at python.org >> https://mail.python.org/mailman/listinfo/matplotlib-users >> > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users -------------- next part -------------- A non-text attachment was scrubbed... Name: Demo_Jean-Philippe_GRIVET.pdf Type: application/pdf Size: 183486 bytes Desc: not available URL: From vincent.adrien at gmail.com Wed Mar 15 05:46:08 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Wed, 15 Mar 2017 10:46:08 +0100 Subject: [Matplotlib-users] axes properties In-Reply-To: <58C80F8A.1080800@phpandmore.net> References: <466328615.7894.1489254867743.JavaMail.www@wwinf1k15> <58C80F8A.1080800@phpandmore.net> Message-ID: <58C90D60.5030300@gmail.com> Hello Jean-Philippe, To complete Amit's reply and in case nobody else already answered your other question, you can have a look at the following example (the output is attached as a PDF) that shows: - How to define tick locators, which can be useful for example when you do not know in advance what exact values the ticks should have. Please find more informations in the [official docs](http://matplotlib.org/api/ticker_api.html). You may also find of interest these recent examples, about: * [tick locators](http://matplotlib.org/examples/ticks_and_spines/tick-locators.html); * [tick formatters](matplotlib.org/examples/ticks_and_spines/tick-formatters.html); - How to invert one of the axes (the z-axis in the example). ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import (LinearLocator, MaxNLocator, MultipleLocator) def dummy_plot(ax): X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25)) Z = np.sin(np.sqrt(X**2 + Y**2)) ax.plot_surface(X, Y, Z, cmap='coolwarm') return ax fig = plt.figure("Demo_Jean-Philippe_GRIVET", figsize=(4.8 * 3, 4.8)) ax0 = fig.add_subplot(1, 3, 1, projection='3d') ax0 = dummy_plot(ax0) ax0.set_title('Vanilla plot') ax1 = fig.add_subplot(1, 3, 2, projection='3d') ax1 = dummy_plot(ax1) ax1.set_title('Custom locators') ax1.set_xlabel('LinearLocator') # evenly spaced ticks from min to max ax1.xaxis.set_major_locator(LinearLocator(numticks=5)) ax1.set_ylabel('MaxNLocator') # use up to nbins+1 ticks at nice locs ax1.yaxis.set_major_locator(MaxNLocator(nbins=5, symmetric=True, integer=True)) ax1.set_zlabel('MultipleLocator') # ticks/range are a multiple of base ax1.zaxis.set_major_locator(MultipleLocator(base=0.4)) ax2 = fig.add_subplot(1, 3, 3, projection='3d') ax2 = dummy_plot(ax2) ax2.set_title('Inverted z-axis') ax2.invert_zaxis() # From looking at the code, it is equivalent to: # bottom, top = ax2.get_zlim() # ax2.set_zlim(top, bottom, auto=None) plt.tight_layout() plt.show() ``` Best, Adrien On 14/03/2017 16:43, Amit Yaron wrote: > Try using the methods 'set_xticks', 'set_yticks' and 'set_zticks' of the > Axes object. > Each of them accepts a list of values that will be displayed. > For example: > ax.set_xticks(np.r_[-10:10:3j]) > > Will display ticks for values -10,0 and 10 only. > > > On 11/03/17 19:54, Jean-Philippe GRIVET wrote: >> Hello, >> >> I have two questions related to axes in a 3-D plot. >> >> 1. I often find that ticks are too close together so that labels >> overlap. How >> can I change the number of ticks or the step length ? >> >> 2. The default axes lay-out has x increasing from left to right and y >> increasing >> from front to back. My finction decrease quickly with increasing y, so >> that the >> corresponding parts of the surface are hidden. Therefore, I would like >> to have >> y values increasing from back to front. I understand that yaxis_invert >> can do it >> but how is it used ? >> >> Thank you for your help >> Jean-Philippe >> >> >> >> _______________________________________________ >> Matplotlib-users mailing list >> Matplotlib-users at python.org >> https://mail.python.org/mailman/listinfo/matplotlib-users >> > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users -------------- next part -------------- A non-text attachment was scrubbed... Name: Demo_Jean-Philippe_GRIVET.pdf Type: application/pdf Size: 183486 bytes Desc: not available URL: From jean-philippe.grivet at wanadoo.fr Sat Mar 18 12:56:17 2017 From: jean-philippe.grivet at wanadoo.fr (Jean-Philippe GRIVET) Date: Sat, 18 Mar 2017 17:56:17 +0100 (CET) Subject: [Matplotlib-users] axes properties Message-ID: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> Thank you so much Vincent? (and Amit) for your detailed answers. I have two questions remaining. ? 1. All the code examples that I have looked at (including the "getting started" example on page 1798 of the user manual for Matplotlib 2.0) uses the "add_subplot" metod. Why should a 3d projection be included in a subplot and not in a plot ? ? 2. In all the examples, the figure seems to be viewed down the 1,1,1 direction towards the origin. How can the view point be changed from within the program ? ? Thanks again, Jean-Philippe ? ? ? ? ? ? ? ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent.adrien at gmail.com Tue Mar 21 09:57:14 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Tue, 21 Mar 2017 14:57:14 +0100 Subject: [Matplotlib-users] axes properties In-Reply-To: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> References: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> Message-ID: <58D1313A.3060806@gmail.com> Dear Jean-Philippe, (If I correctly understood your question 1.:) `fig.add_subplot` creates an Axes instance where you can then plot more or less *any* kind of plot that Matplotlib supports (line, scatter, hist, patch, etc.). *It is not specific to the '3d' projection.* `fig.add_subplot(1, 1, 1)` (or `fig.add_subplot(111)` if your prefer a syntax closer to MATLAB) simply means that you want to create a single (sub)plot area on your figure canvas. If you are confused because in 2D you could get a line plot simply with `plt.plot([0, 1, 2])`, understand that under the hood it is only some kind of wrapper for the (OO-)equivalent: ```python fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot([0, 1, 2]) ``` The difference here to get a 3D Axes instance is that you have to precise the projection when you create it (`fig.add_subplot(1, 1, 1, projection='3d')`). Besides (if I am correct), please note that ?we? tend to promote using an equivalent (but more OO-)wrapper, namely `plt.subplots` (the final *s* is important!). In 2D, you can thus write ```python fig, ax = plt.subplots() # create a "111-subplot" ax.plot([0, 1, 2]) ``` and you can pass different **kwargs to it, among which a 'subplot_kw' dictionary that allows you to precise the projection. For example if you want to get a "111-subplot" 3d Axes: ``` fig, ax = plt.subplots(subplot_kw={'projection': '3d'}) ``` It is a bit verbose is this simple situation but becomes rather convenient for grids with several subplots. About 2. you may want to have a look at the following properties and methods: - ax.dist - ax.azim - ax.elev - ax.view_init(elev=..., azim=...) Here is a small script (PNG output is attached) that demonstrate their usage: ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def dummy_plot(ax): X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25)) Z = np.sin(np.sqrt(X**2 + Y**2)) ax.plot_surface(X, Y, Z, cmap='coolwarm') # Remove all the ticks for eye pleasure ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) ax.zaxis.set_major_locator(plt.NullLocator()) return ax # Here is a way to instantiate all the 2x2 subplots at once, without using # the `fig.add_subplot` method. *axs* is a 2x2-array of Axes instances. fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(6.4, 4.8), num="Demo_Jean-Philippe_GRIVET_2", # <- figure label subplot_kw={'projection': '3d'}) ax = dummy_plot(axs[0, 0]) ax.set_title("Forced defaults: dist=10 (a.u.),\nazim=-60 (deg), elev=30 (deg)") # NB: these values does not seem to be exactly the (1, 1, 1) direction to me. ax.dist = 10 ax.view_init(azim=-60, elev=30) # From the docstring of `ax.view_init`: # Set the elevation and azimuth of the axes. This can be used to rotate # the axes programatically: # - 'elev' stores the elevation angle in the z plane. # - 'azim' stores the azimuth angle in the x,y plane. ax = dummy_plot(axs[0, 1]) ax.set_title("Doubled 'dist' value") ax.dist *= 2 # NB: one can also directly set the `ax.azim` and `ax.elev` properties ax = dummy_plot(axs[1, 0]) ax.set_title("'azim' increased of 45 deg.") ax.azim += 45 ax = dummy_plot(axs[1, 1]) ax.set_title("'elev' set to 60 deg.") ax.elev = 60 plt.tight_layout() plt.show() ``` Hopefully it will help you to plot what you want :). Best, Adrien On 18/03/2017 17:56, Jean-Philippe GRIVET wrote: > Thank you so much Vincent (and Amit) for your detailed answers. > > I have two questions remaining. > > 1. All the code examples that I have looked at (including the "getting > started" example on page 1798 of the user manual for Matplotlib 2.0) > uses the "add_subplot" metod. Why should a 3d projection be included > in a subplot and not in a plot ? > > 2. In all the examples, the figure seems to be viewed down the 1,1,1 > direction towards the origin. How can the view point be changed from > within the program ? > > Thanks again, > Jean-Philippe -------------- next part -------------- A non-text attachment was scrubbed... Name: Demo_Jean-Philippe_GRIVET_2.png Type: image/png Size: 128810 bytes Desc: not available URL: From ben.v.root at gmail.com Tue Mar 21 10:21:44 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Tue, 21 Mar 2017 10:21:44 -0400 Subject: [Matplotlib-users] axes properties In-Reply-To: <58D1313A.3060806@gmail.com> References: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> <58D1313A.3060806@gmail.com> Message-ID: Jean-Philippe, To answer your second question, you can use the `view_init()` method of the axes to change the orientation of the axes: http://matplotlib.org/mpl_toolkits/mplot3d/api.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init An example using it to do a "rotation": http://matplotlib.org/examples/mplot3d/rotate_axes3d_demo.html I hope that helps! Ben Root On Tue, Mar 21, 2017 at 9:57 AM, vincent.adrien at gmail.com < vincent.adrien at gmail.com> wrote: > Dear Jean-Philippe, > > (If I correctly understood your question 1.:) `fig.add_subplot` creates an > Axes > instance where you can then plot more or less *any* kind of plot that > Matplotlib > supports (line, scatter, hist, patch, etc.). *It is not specific to the > '3d' > projection.* `fig.add_subplot(1, 1, 1)` (or `fig.add_subplot(111)` if your > prefer a syntax closer to MATLAB) simply means that you want to create a > single > (sub)plot area on your figure canvas. If you are confused because in 2D you > could get a line plot simply with `plt.plot([0, 1, 2])`, understand that > under > the hood it is only some kind of wrapper for the (OO-)equivalent: > ```python > fig = plt.figure() > ax = fig.add_subplot(1, 1, 1) > ax.plot([0, 1, 2]) > ``` > The difference here to get a 3D Axes instance is that you have to precise > the > projection when you create it (`fig.add_subplot(1, 1, 1, > projection='3d')`). > > Besides (if I am correct), please note that ?we? tend to promote using an > equivalent (but more OO-)wrapper, namely `plt.subplots` (the final *s* is > important!). In 2D, you can thus write > ```python > fig, ax = plt.subplots() # create a "111-subplot" > ax.plot([0, 1, 2]) > ``` > and you can pass different **kwargs to it, among which a 'subplot_kw' > dictionary > that allows you to precise the projection. For example if you want to get a > "111-subplot" 3d Axes: > ``` > fig, ax = plt.subplots(subplot_kw={'projection': '3d'}) > ``` > It is a bit verbose is this simple situation but becomes rather convenient > for > grids with several subplots. > > About 2. you may want to have a look at the following properties and > methods: > - ax.dist > - ax.azim > - ax.elev > - ax.view_init(elev=..., azim=...) > > Here is a small script (PNG output is attached) that demonstrate their > usage: > ```python > import numpy as np > import matplotlib.pyplot as plt > from mpl_toolkits.mplot3d import Axes3D > > > def dummy_plot(ax): > X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25)) > Z = np.sin(np.sqrt(X**2 + Y**2)) > ax.plot_surface(X, Y, Z, cmap='coolwarm') > # Remove all the ticks for eye pleasure > ax.xaxis.set_major_locator(plt.NullLocator()) > ax.yaxis.set_major_locator(plt.NullLocator()) > ax.zaxis.set_major_locator(plt.NullLocator()) > return ax > > # Here is a way to instantiate all the 2x2 subplots at once, without using > # the `fig.add_subplot` method. *axs* is a 2x2-array of Axes instances. > fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(6.4, 4.8), > num="Demo_Jean-Philippe_GRIVET_2", # <- figure > label > subplot_kw={'projection': '3d'}) > > ax = dummy_plot(axs[0, 0]) > ax.set_title("Forced defaults: dist=10 (a.u.),\nazim=-60 (deg), elev=30 > (deg)") > # NB: these values does not seem to be exactly the (1, 1, 1) direction to > me. > ax.dist = 10 > ax.view_init(azim=-60, elev=30) > # From the docstring of `ax.view_init`: > # Set the elevation and azimuth of the axes. This can be used to rotate > # the axes programatically: > # - 'elev' stores the elevation angle in the z plane. > # - 'azim' stores the azimuth angle in the x,y plane. > > ax = dummy_plot(axs[0, 1]) > ax.set_title("Doubled 'dist' value") > ax.dist *= 2 > > # NB: one can also directly set the `ax.azim` and `ax.elev` properties > ax = dummy_plot(axs[1, 0]) > ax.set_title("'azim' increased of 45 deg.") > ax.azim += 45 > > ax = dummy_plot(axs[1, 1]) > ax.set_title("'elev' set to 60 deg.") > ax.elev = 60 > > plt.tight_layout() > plt.show() > ``` > > Hopefully it will help you to plot what you want :). > > Best, > Adrien > > On 18/03/2017 17:56, Jean-Philippe GRIVET wrote: > > Thank you so much Vincent (and Amit) for your detailed answers. > > > > I have two questions remaining. > > > > 1. All the code examples that I have looked at (including the "getting > > started" example on page 1798 of the user manual for Matplotlib 2.0) > > uses the "add_subplot" metod. Why should a 3d projection be included > > in a subplot and not in a plot ? > > > > 2. In all the examples, the figure seems to be viewed down the 1,1,1 > > direction towards the origin. How can the view point be changed from > > within the program ? > > > > Thanks again, > > Jean-Philippe > > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fgbadamosi at ymail.com Tue Mar 21 12:17:57 2017 From: fgbadamosi at ymail.com (Gbadamosi Farouk) Date: Tue, 21 Mar 2017 17:17:57 +0100 Subject: [Matplotlib-users] (no subject) Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From jean-philippe.grivet at wanadoo.fr Wed Mar 22 13:57:37 2017 From: jean-philippe.grivet at wanadoo.fr (Jean-Philippe Grivet) Date: Wed, 22 Mar 2017 18:57:37 +0100 Subject: [Matplotlib-users] axes properties In-Reply-To: References: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> <58D1313A.3060806@gmail.com> Message-ID: <58D2BB11.9090008@wanadoo.fr> Thanks a lot Benjamin and Vincent for your most kind and detailed answers. In reply to Vincent, I regret that the authors of Matplotkib did not pursue the wrapper idea and propose a function plot3d(x,y,z); it would make life simpler. I copied from the net (I can't remember where) the following code fragment: from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as pt fig = pt.figure() ax = fig.gca(projection='3d') ................ surf = ax.plot_wireframe(X, Y, Z, rstride = 10,cstride = 10) which looks rather similar to Matlab syntax and works well for me. Is that considered to be obsolete or in bad style ? Thanks again, Jean-Philippe From ben.v.root at gmail.com Wed Mar 22 15:15:51 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Wed, 22 Mar 2017 15:15:51 -0400 Subject: [Matplotlib-users] axes properties In-Reply-To: <58D2BB11.9090008@wanadoo.fr> References: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> <58D1313A.3060806@gmail.com> <58D2BB11.9090008@wanadoo.fr> Message-ID: fig.gca(projection='3d') is perfectly valid, but you need to realize what it does. It will only work if it is a single plot in the figure, and that that is the *first* reference to the plot. If some other plotting action has already happened, then it wouldn't work, because fig.gca() means "get the current axes in the figure, if it exists; if it doesn't exist yet, create one with these parameters". So, if an axes already exists, then it'll fetch that one, and it may not be a 3d axes. Also, if you plan to do subplots, then `gca()` may be limiting since it is not explicit about which subplot in a figure it is referring to. Cheers! Ben Root On Wed, Mar 22, 2017 at 1:57 PM, Jean-Philippe Grivet < jean-philippe.grivet at wanadoo.fr> wrote: > Thanks a lot Benjamin and Vincent for your most kind and detailed answers. > > In reply to Vincent, I regret that the authors of Matplotkib did not pursue > the wrapper idea and propose a function plot3d(x,y,z); it would make life > simpler. > > I copied from the net (I can't remember where) the following code fragment: > > from mpl_toolkits.mplot3d import Axes3D > import numpy as np > import matplotlib.pyplot as pt > > fig = pt.figure() > ax = fig.gca(projection='3d') > ................ > surf = ax.plot_wireframe(X, Y, Z, rstride = 10,cstride = 10) > > which looks rather similar to Matlab syntax and works well for me. > Is that considered to be obsolete or in bad style ? > > Thanks again, > Jean-Philippe > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent.adrien at gmail.com Wed Mar 22 15:49:26 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Wed, 22 Mar 2017 20:49:26 +0100 Subject: [Matplotlib-users] axes properties In-Reply-To: <58D2BB11.9090008@wanadoo.fr> References: <1579036935.8891.1489856177557.JavaMail.www@wwinf1j16> <58D1313A.3060806@gmail.com> <58D2BB11.9090008@wanadoo.fr> Message-ID: <58D2D546.7000202@gmail.com> Hello Jean-Philippe, >From my point of view, coding style only (really) matters if you intend to share your code with other people. If you are and will ever be the only writer and reader of your own code, then I would be inclined to say that as long as you are comfortable with it, you can code as you wish ;). A remaining problem that may still remain though is if you go asking questions on forums, Stack Overflow, etc., where people may expect you to write code that follows some guidelines. In Python, the guidelines are commonly those from the [PEP8](https://www.python.org/dev/peps/pep-0008/). A very loose summary and yet quite sufficient for a day-to-day use might be: - 'my_variable' and 'my_function' vs 'MyClass' for the naming schemes; - '_nonpublic_method()' vs 'public_method()' for classe method names - wrap long lines into smaller ones (usually < 80 characters); - use 4 spaces (instead of tab) per indentation level; - mostly use whitespaces around binary operators and except in a few situations: - my_function(arg_1, kwarg_1=val_1, kwarg_2=val_2) (no space around '=') - 'res = a*b +c*d' is better than 'res = a * b + c * d' - my_dict = {key_1: item_1, key_2: item_2}, i.e. 'key: item' Concerning Matplotlib conventions, I would say that the common use is to import pyplot as 'plt', not 'pt'. ``` import matplotlib.pyplot as plt ``` It is true that we try in our current documentation to promote the object-oriented interface (OO-interface), which usually make things clearer when you write scripts (you explicitely know where the drawing will be performed for example): ``` # Either with the most recent wrapper: fig, ax = plt.subplots() ax. plot([0, 2, 1]) # or following the older but still perfectly OK fashion: fig = plt.figure() ax = fig.add_subplot(111) ax.plot([0, 2, 1]) ``` However, at least for 2D plots, you can definitively use the more MATLAB-like fashion, i.e. ``` plt.plot([0, 2, 1]) ``` which will implicitly draw in the current Axes instance, and create one , as well as a Figure one, if none already exists. In the case of mplot3d, I may be wrong but I think that you have to use at least partially the OO-interface. Except for a few points stated above, I would say that your code snippet should still be perfectly OK for a long time :). Here is a version with the small style fixes I would suggest: ``` import numpy as np import matplotlib.pyplot as plt # 'pt' <- 'plt' from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() # 'pt' <- 'plt' ax = fig.gca(projection='3d') # yada yada yada surf = ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) # no space around '=' ``` And if you really want concise code (for example during an interactive session), I think you can achieve things that are rather close to MATLAB (at least from what I remember), like: ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Just for demonstration sake, we create dummy data with a convenient helper from mpl_toolkits.mplot3d.axes3d import get_test_data X, Y, Z = get_test_data(0.05) # Straightforward case with a single 3D-plot ax = plt.gca(projection='3d') # a figure is created implicitly if none exists ax.plot_wireframe(X, Y, Z) plt.title("Single plot") # <=> ax.set_title("Single plot") # Straightforward case with 1x2 subplots. plt.figure() # new figure, just to avoid drawing in the previous one ax = plt.subplot(121, projection='3d') ax.plot_wireframe(X, Y, Z) plt.title("1st subplot:\ndefault parameters") ax = plt.subplot(122, projection='3d') ax.plot_wireframe(X, Y, Z, cstride=10, rstride=5) plt.title("2nd subplot:\ncustom parameters") ``` Regards, Adrien On 22/03/2017 18:57, Jean-Philippe Grivet wrote: > Thanks a lot Benjamin and Vincent for your most kind and detailed answers. > > In reply to Vincent, I regret that the authors of Matplotkib did not pursue > the wrapper idea and propose a function plot3d(x,y,z); it would make life simpler. > > I copied from the net (I can't remember where) the following code fragment: > > from mpl_toolkits.mplot3d import Axes3D > import numpy as np > import matplotlib.pyplot as pt > > fig = pt.figure() > ax = fig.gca(projection='3d') > ................ > surf = ax.plot_wireframe(X, Y, Z, rstride = 10,cstride = 10) > > which looks rather similar to Matlab syntax and works well for me. > Is that considered to be obsolete or in bad style ? > > Thanks again, > Jean-Philippe > > From mobiusklein at gmail.com Wed Mar 22 16:41:48 2017 From: mobiusklein at gmail.com (Joshua Klein) Date: Wed, 22 Mar 2017 16:41:48 -0400 Subject: [Matplotlib-users] Arbitrary artist data on SVG elements Message-ID: Hello, I often embed figures as SVG graphics in web pages. As part of this process, I usually do the following 1. Set gids on artists and link that gid to a set of data describing that part of a graphic in an external dictionary. This includes things like setting the element?s class, extra contextual information, information that would be good to show in a tooltip, ids of related elements, and so forth. 2. Serialize the figure into a file-like object, use an element tree implementation?s XMLID to get an element id map and Element objects 3. Iterate over my data dictionary from (1) and set keys in the mapped Element?s attrib dictionary, using the id map from (2) 4. Use the element tree implementation?s tostring function to serialize the updated Element objects back into a string and then send the string out as a response to a web request. 5. After receiving the SVG string from the server on the client, add the SVG to the page?s DOM and then hang event handlers on it (or pre-specify delegated handlers) that use the added attributes to configure interactive behavior. I looked at the Artist type and saw no good place to store ?arbitrary data?. Before I start working on this I wanted to know if anyone else had a better solution. I would also like to know if the devs would be opposed to a PR that adds an extra dictionary/attribute to every Artist instance created. Another alternative solution would be to find a way to push my dictionary mapping gids to extra attributes into the SVGRenderer and have it pass them as **extras to XMLWriter.element when it processes individual artists. Here?s a generic example of what I do currently: def plot_with_extras_for_svg(*data, **kwargs): # Do the plotting, generating the id-linked data in `id_mapper` ax, id_mapper = plot_my_data(*data, **kwargs) xlim = ax.get_xlim() ylim = ax.get_ylim() # compute the total space used in both dimensions when dealing with # negative axis bounds x_size = sum(map(abs, xlim)) y_size = sum(map(abs, ylim)) # Map the used axis space to the drawable region dimensions aspect_ratio = x_size / y_size canvas_x = 8. canvas_y = canvas_x / aspect_ratio # Configure the artist to draw within the new drawable region bounds fig = ax.get_figure() fig.tight_layout(pad=0.2) fig.patch.set_visible(False) fig.set_figwidth(canvas_x) fig.set_figheight(canvas_y) ax.patch.set_visible(False) # Perform the first serialization buff = StringIO() fig.savefig(buff, format='svg') # Parse XML buffer from `buff` and configure tag attributes root, ids = ET.XMLID(buff.getvalue()) root.attrib['class'] = 'plot-class-svg' for id, attributes in id_mapper.items(): element = ids[id] element.attrib.update({("data-" + k): str(v) for k, v in attributes.items()}) element.attrib['class'] = id.rsplit('-')[0] # More drawable space shenanigans min_x, min_y, max_x, max_y = map(int, root.attrib["viewBox"].split(" ")) min_x += 100 max_x += 200 view_box = ' '.join(map(str, (min_x, min_y, max_x, max_y))) root.attrib["viewBox"] = view_box width = float(root.attrib["width"][:-2]) * 1.75 root.attrib["width"] = "100%" height = width / (aspect_ratio) root.attrib["height"] = "%dpt" % (height * 1.2) root.attrib["preserveAspectRatio"] = "xMinYMin meet" # Second serialization svg = ET.tostring(root) plt.close(fig) return svg Thank you ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mailinglists at xgm.de Thu Mar 23 09:24:31 2017 From: mailinglists at xgm.de (Florian Lindner) Date: Thu, 23 Mar 2017 14:24:31 +0100 Subject: [Matplotlib-users] Making a solid legend Message-ID: Hello, I try to make the legend non-translucent, having a solid color and laying above the plot itself. That's what I try: import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1.plot([0, 1], [0, 2], label = "Plot 1") leg = ax1.legend(loc = 1) leg.get_frame().set_facecolor("r") leg.set_alpha(0) plt.grid() plt.show() (you may have to pan the plot) Taken from: http://matplotlib.org/examples/api/legend_demo.html http://matplotlib.org/1.3.0/examples/pylab_examples/legend_translucent.html The set_alpha seems to have no effect at all. facecolor works, but it is always translucent. Thanks, Florian From vincent.adrien at gmail.com Thu Mar 23 09:38:08 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Thu, 23 Mar 2017 14:38:08 +0100 Subject: [Matplotlib-users] Making a solid legend In-Reply-To: References: Message-ID: <58D3CFC0.4020104@gmail.com> Hello Florian, A `get_frame()` call seems to be missing in your example. Try with ``` leg.get_frame().set_facecolor('r') ``` Note that you can also directly set this when calling `legend`: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0, 1], label='Plot 1') leg = ax.legend(loc='upper left', framealpha=1.0, facecolor='red') ax.grid() plt.show() ``` If you want to fix this for every plot you do, you may want to tweak your matplotlibrc file or at least the related rcParams in your scrpit, which are 'legend.framecolor' and 'legend.framealpha'. Best regards, Adrien On 23/03/2017 14:24, Florian Lindner wrote: > Hello, > > I try to make the legend non-translucent, having a solid color and laying above the plot itself. > > That's what I try: > > > import matplotlib.pyplot as plt > > fig, ax1 = plt.subplots() > ax1.plot([0, 1], [0, 2], label = "Plot 1") > > leg = ax1.legend(loc = 1) > leg.get_frame().set_facecolor("r") > leg.set_alpha(0) > > plt.grid() > plt.show() > > > (you may have to pan the plot) > > Taken from: > http://matplotlib.org/examples/api/legend_demo.html > http://matplotlib.org/1.3.0/examples/pylab_examples/legend_translucent.html > > The set_alpha seems to have no effect at all. facecolor works, but it is always translucent. > > Thanks, > Florian > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > From mailinglists at xgm.de Thu Mar 23 10:10:25 2017 From: mailinglists at xgm.de (Florian Lindner) Date: Thu, 23 Mar 2017 15:10:25 +0100 Subject: [Matplotlib-users] Making a solid legend In-Reply-To: <58D3CFC0.4020104@gmail.com> References: <58D3CFC0.4020104@gmail.com> Message-ID: <36746729-0e6c-5ad9-4c5e-12d6f2ecece7@xgm.de> Hello, Am 23.03.2017 um 14:38 schrieb vincent.adrien at gmail.com: > Hello Florian, > > A `get_frame()` call seems to be missing in your example. Try with > ``` > leg.get_frame().set_facecolor('r') > ``` > > Note that you can also directly set this when calling `legend`: > ``` > import matplotlib.pyplot as plt > > fig, ax = plt.subplots() > ax.plot([0, 1], label='Plot 1') > > leg = ax.legend(loc='upper left', framealpha=1.0, facecolor='red') > > ax.grid() > plt.show() > ``` > > If you want to fix this for every plot you do, you may want to tweak your > matplotlibrc file or at least the related rcParams in your scrpit, which are > 'legend.framecolor' and 'legend.framealpha'. Oh, cool, that is what I was looking for too. I found out that my original issue is also related to twinx: import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1.plot([0, 1], [0, 2], label = "Plot 1 with some more text") ax1.legend(framealpha = 1, bbox_to_anchor = (0.1, 1)) ax2 = ax1.twinx() ax2.plot([0, 1], [2.2, 0], "--", label = "Plot 2 with some more text") ax2.legend(framealpha = 1, bbox_to_anchor = (1.1,1)) plt.grid() plt.show() The second legend is over the right y-axis, the first legend is not over the left y-axis. Can I set legends in a way they are always above any element? Thanks, Florian > Best regards, > Adrien > > On 23/03/2017 14:24, Florian Lindner wrote: >> Hello, >> >> I try to make the legend non-translucent, having a solid color and laying above the plot itself. >> >> That's what I try: >> >> >> import matplotlib.pyplot as plt >> >> fig, ax1 = plt.subplots() >> ax1.plot([0, 1], [0, 2], label = "Plot 1") >> >> leg = ax1.legend(loc = 1) >> leg.get_frame().set_facecolor("r") >> leg.set_alpha(0) >> >> plt.grid() >> plt.show() >> >> >> (you may have to pan the plot) >> >> Taken from: >> http://matplotlib.org/examples/api/legend_demo.html >> http://matplotlib.org/1.3.0/examples/pylab_examples/legend_translucent.html >> >> The set_alpha seems to have no effect at all. facecolor works, but it is always translucent. >> >> Thanks, >> Florian >> >> _______________________________________________ >> Matplotlib-users mailing list >> Matplotlib-users at python.org >> https://mail.python.org/mailman/listinfo/matplotlib-users >> From vincent.adrien at gmail.com Thu Mar 23 11:01:53 2017 From: vincent.adrien at gmail.com (vincent.adrien at gmail.com) Date: Thu, 23 Mar 2017 16:01:53 +0100 Subject: [Matplotlib-users] Making a solid legend In-Reply-To: <36746729-0e6c-5ad9-4c5e-12d6f2ecece7@xgm.de> References: <58D3CFC0.4020104@gmail.com> <36746729-0e6c-5ad9-4c5e-12d6f2ecece7@xgm.de> Message-ID: <58D3E361.70104@gmail.com> I am not an expert of the legend codebase but it seems like you can achieve this with the following snippet heavily insprired from this [SO thread](http://stackoverflow.com/questions/25829736/matplotlib-how-to-adjust-zorder-of-second-legend) and the Matplotlib [tutorial on legend](http://matplotlib.org/users/legend_guide.html). In a nutshell, you build a legend-like artist similar to the one of the first axes and display it into the second axis. ``` import matplotlib.pyplot as plt plt.rcParams['legend.framealpha'] = 1.0 plt.rcParams['legend.facecolor'] = '0.95' fig, ax1 = plt.subplots() ax1.plot([0, 1], [0, 2], label="Plot 1") ax2 = ax1.twinx() ax2.plot([0, 1], [2.2, 0], "--", label="Plot 2") ax2.legend(bbox_to_anchor=(1, 1)) # Manually add *leg1*, the legend of *ax1*, to *ax2* so it displays "on top" handles1, labels1 = ax1.get_legend_handles_labels() leg1 = plt.legend(handles1, labels1, loc="upper left", bbox_to_anchor=(0, 1)) ax2.add_artist(leg1) # `loc="upper left"` (or anything but "best") is highly recommended, as it # determines which part of the bbox is anchored to the desired coordinates. # "best" (the new default btw.) could lead to weird behaviors when changing # just a bit the anchor position... # Just in case: here is a simple way to display a single common legend. # Note the it will replace the previous legend on *ax2*. #handles1, labels1 = ax1.get_legend_handles_labels() #handles2, labels2 = ax2.get_legend_handles_labels() #ax2.legend(handles1+handles2, labels1+labels2, loc="lower center") plt.grid() plt.show() ``` Best, Adrien PS: I made a mistake in my previous email. The correct rcParams key are 'legend.framealpha' and *'legend.facecolor'* (not 'legend.framecolor'). On 23/03/2017 15:10, Florian Lindner wrote: > Hello, > > > Am 23.03.2017 um 14:38 schrieb vincent.adrien at gmail.com: >> Hello Florian, >> >> A `get_frame()` call seems to be missing in your example. Try with >> ``` >> leg.get_frame().set_facecolor('r') >> ``` >> >> Note that you can also directly set this when calling `legend`: >> ``` >> import matplotlib.pyplot as plt >> >> fig, ax = plt.subplots() >> ax.plot([0, 1], label='Plot 1') >> >> leg = ax.legend(loc='upper left', framealpha=1.0, facecolor='red') >> >> ax.grid() >> plt.show() >> ``` >> >> If you want to fix this for every plot you do, you may want to tweak your >> matplotlibrc file or at least the related rcParams in your scrpit, which are >> 'legend.framecolor' and 'legend.framealpha'. > > Oh, cool, that is what I was looking for too. > > I found out that my original issue is also related to twinx: > > import matplotlib.pyplot as plt > > fig, ax1 = plt.subplots() > ax1.plot([0, 1], [0, 2], label = "Plot 1 with some more text") > ax1.legend(framealpha = 1, bbox_to_anchor = (0.1, 1)) > > ax2 = ax1.twinx() > ax2.plot([0, 1], [2.2, 0], "--", label = "Plot 2 with some more text") > ax2.legend(framealpha = 1, bbox_to_anchor = (1.1,1)) > > plt.grid() > plt.show() > > The second legend is over the right y-axis, the first legend is not over the left y-axis. > > Can I set legends in a way they are always above any element? > > Thanks, > Florian > > > >> Best regards, >> Adrien >> >> On 23/03/2017 14:24, Florian Lindner wrote: >>> Hello, >>> >>> I try to make the legend non-translucent, having a solid color and laying above the plot itself. >>> >>> That's what I try: >>> >>> >>> import matplotlib.pyplot as plt >>> >>> fig, ax1 = plt.subplots() >>> ax1.plot([0, 1], [0, 2], label = "Plot 1") >>> >>> leg = ax1.legend(loc = 1) >>> leg.get_frame().set_facecolor("r") >>> leg.set_alpha(0) >>> >>> plt.grid() >>> plt.show() >>> >>> >>> (you may have to pan the plot) >>> >>> Taken from: >>> http://matplotlib.org/examples/api/legend_demo.html >>> http://matplotlib.org/1.3.0/examples/pylab_examples/legend_translucent.html >>> >>> The set_alpha seems to have no effect at all. facecolor works, but it is always translucent. >>> >>> Thanks, >>> Florian >>> >>> _______________________________________________ >>> Matplotlib-users mailing list >>> Matplotlib-users at python.org >>> https://mail.python.org/mailman/listinfo/matplotlib-users >>> > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > From filaton at me.com Mon Mar 27 09:27:15 2017 From: filaton at me.com (Jean CRUYPENYNCK) Date: Mon, 27 Mar 2017 15:27:15 +0200 Subject: [Matplotlib-users] How is GUI startup implemented? Message-ID: <697F21A6-D789-4A12-B1FD-1151A5B417F4@me.com> Hi all! I?m currently writing some Python/C++ library using Boost.Python on macOS. When I import it, I get the ?famous rocket icon? bouncing in the macOS Dock and I can?t understand why. I know that this icon appears on macOS when Python detects that a program will interact with the GUI. It?s something that happens with matplotlib as well, when running from matplotlib import pyplot with the default backend. I?m wondering how this behavior is implemented, i.e. where in the source code does matplotlib call the GUI process when I execute the from matplotlib import pyplot statement? I believe that could help me solving my problem with Boost.Python. Thank you in advance for your answer, Jean. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmssnyder at ucdavis.edu Wed Mar 29 15:51:59 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Wed, 29 Mar 2017 19:51:59 +0000 Subject: [Matplotlib-users] segmentation fault problems with basemap Message-ID: Whenever I run a python with basemap I get a segmentation fault error. For example when running: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. # set resolution=None to skip processing of boundary datasets. m = Basemap(width=12000000,height=9000000,projection='lcc', resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) # draw a land-sea mask for a map background. # lakes=True means plot inland lakes with ocean color. m.drawlsmask(land_color='coral',ocean_color='aqua',lakes=True) plt.show() I get a segmentation fault core dump error. I have done some reading online about this and they say that it could be because I accidently installed two versions of geos ( http://trac.osgeo.org/geos/), which include geos.3.3.6 and geos.3.3.3 which was already available in the basemap package. Could this be the problem that is creating the segmentation fault core dump? If so how do I uninstall the geos libraries that I do not need. There is not a lot of specific information on how to uninstall geos libraries and I really need a specific guide on how to do this and get the above script working properly. -- Jason Snyder PhD -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmssnyder at ucdavis.edu Wed Mar 29 20:16:23 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Thu, 30 Mar 2017 00:16:23 +0000 Subject: [Matplotlib-users] basemap projection issues Message-ID: I am trying to draw a map across the Atlantic Ocean from the eastern seaboard to Europe. I also want to draw a map across the Pacific Ocean including both sides of the dataline using the basemap utility. Unfortunately there is very limited information on how to do this. I am not sure what project would be best. For instance I want to draw a map with a latitude from 20 to 50 degrees and a longitude from 40 E to 120 W. Using the basemap utility how do I go about doing this? -- Jason Snyder PhD -------------- next part -------------- An HTML attachment was scrubbed... URL: From xubinrun at gmail.com Wed Mar 29 23:16:54 2017 From: xubinrun at gmail.com (Xu, Bin) Date: Thu, 30 Mar 2017 11:16:54 +0800 Subject: [Matplotlib-users] bug for savefig to eps in the latest version of matplotlib In-Reply-To: References: Message-ID: <07401b7b-992b-d339-0959-6e0662e5fdc8@gmail.com> Dear all, I recently update my matplotlib to the latest version, and found pyplot.savefig to eps file didn't work well like previous version. Test script: ================================== #!/usr/bin/python -tt from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import numpy as np # normal distribution center at x=0 and y=5 x = np.random.randn(100000) y = np.random.randn(100000) + 5 plt.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar() #plt.show() plt.savefig('test.eps') #plt.savefig('test.png') ================================== The result of plt.show() is just like the result of test.png, while test.eps has a weired large file size (more than 20 MB in other case). In the meantime, the facecolor for 'NaN' value in test.eps is black, different from test.png and previous version. I consider it is a bug here. How to reach the desired style (regular size, and white color for 'NaN' value in image)? Thanks a lot. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Xu,Bin -------------- next part -------------- A non-text attachment was scrubbed... Name: test.png Type: image/png Size: 13757 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.eps Type: image/x-eps Size: 947546 bytes Desc: not available URL: From ben.v.root at gmail.com Thu Mar 30 09:43:03 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Thu, 30 Mar 2017 09:43:03 -0400 Subject: [Matplotlib-users] bug for savefig to eps in the latest version of matplotlib In-Reply-To: <07401b7b-992b-d339-0959-6e0662e5fdc8@gmail.com> References: <07401b7b-992b-d339-0959-6e0662e5fdc8@gmail.com> Message-ID: as a test, can you activate the "classic" mode? I have a suspicion what this bug is. Just add "import matplotlib; matplotlib.use('classic')" before any plotting calls. Ben Root On Wed, Mar 29, 2017 at 11:16 PM, Xu, Bin wrote: > Dear all, > > I recently update my matplotlib to the latest version, and found > pyplot.savefig to eps file didn't work well like previous version. > Test script: > ================================== > #!/usr/bin/python -tt > from matplotlib.colors import LogNorm > import matplotlib.pyplot as plt > import numpy as np > > # normal distribution center at x=0 and y=5 > x = np.random.randn(100000) > y = np.random.randn(100000) + 5 > > plt.hist2d(x, y, bins=40, norm=LogNorm()) > plt.colorbar() > #plt.show() > plt.savefig('test.eps') > #plt.savefig('test.png') > ================================== > The result of plt.show() is just like the result of test.png, while > test.eps has a weired large file size (more than 20 MB in other case). In > the meantime, the facecolor for 'NaN' value in test.eps is black, different > from test.png and previous version. I consider it is a bug here. > How to reach the desired style (regular size, and white color for 'NaN' > value in image)? Thanks a lot. > -- > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Xu,Bin > > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben.v.root at gmail.com Thu Mar 30 09:55:10 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Thu, 30 Mar 2017 09:55:10 -0400 Subject: [Matplotlib-users] basemap projection issues In-Reply-To: References: Message-ID: Jason, Basemap is currently in a long-term deprecation process. It is being maintained mostly for legacy scripts, and for a few features that aren't (yet) available elsewhere. For new development, I would suggest trying Cartopy first. It has a better API and better documentation, although it isn't as feature complete as basemap is. Give Cartopy a try first, and if you can't get it to work there, then you can come back and try basemap. http://scitools.org.uk/cartopy/ The userbase is also more active there, so you might get a faster response to any questions you might have. I am not an expert in projections. I am just making sure that basemap continues to work with numpy and matplotlib. Cheers! Ben Root On Wed, Mar 29, 2017 at 8:16 PM, Jason Snyder wrote: > I am trying to draw a map across the Atlantic Ocean from the eastern > seaboard to Europe. I also want to draw a map across the Pacific Ocean > including both sides of the dataline using the basemap utility. > Unfortunately there is very limited information on how to do this. I am > not sure what project would be best. For instance I want to draw a map > with a latitude from 20 to 50 degrees and a longitude from 40 E to 120 W. > Using the basemap utility how do I go about doing this? > > -- > Jason Snyder PhD > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From xubinrun at gmail.com Thu Mar 30 10:00:57 2017 From: xubinrun at gmail.com (Xu, Bin) Date: Thu, 30 Mar 2017 22:00:57 +0800 Subject: [Matplotlib-users] bug for savefig to eps in the latest version of matplotlib In-Reply-To: References: <07401b7b-992b-d339-0959-6e0662e5fdc8@gmail.com> Message-ID: <0eff43bc-e1dc-2f9f-770c-8db8e6e0e0ae@gmail.com> Dear Ben Root, Thanks for your suggestions. Here, I used "plt.style.use('classic')", but the created eps figure was still similar to previous one or even larger... Incidentally, the matplotlibrc I used is the default matplotlibc in my version 2.0.0. Bin On 03/30/2017 09:43 PM, Benjamin Root wrote: > as a test, can you activate the "classic" mode? I have a suspicion > what this bug is. Just add "import matplotlib; > matplotlib.use('classic')" before any plotting calls. > > Ben Root > > > On Wed, Mar 29, 2017 at 11:16 PM, Xu, Bin > wrote: > > Dear all, > > I recently update my matplotlib to the latest version, and found > pyplot.savefig to eps file didn't work well like previous version. > Test script: > ================================== > #!/usr/bin/python -tt > from matplotlib.colors import LogNorm > import matplotlib.pyplot as plt > import numpy as np > > # normal distribution center at x=0 and y=5 > x = np.random.randn(100000) > y = np.random.randn(100000) + 5 > > plt.hist2d(x, y, bins=40, norm=LogNorm()) > plt.colorbar() > #plt.show() > plt.savefig('test.eps') > #plt.savefig('test.png') > ================================== > The result of plt.show() is just like the result of test.png, > while test.eps has a weired large file size (more than 20 MB in > other case). In the meantime, the facecolor for 'NaN' value in > test.eps is black, different from test.png and previous version. I > consider it is a bug here. > How to reach the desired style (regular size, and white color for > 'NaN' value in image)? Thanks a lot. > -- > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Xu,Bin > > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > > -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Xu,Bin School of Materials Science and Engineering, Shanghai Jiao Tong University, 800 Dongchuan Road, Minhang, Shanghai 200240, China Email: xubinrun at gmail.com, xubin_materials at sjtu.edu.cn ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben.v.root at gmail.com Thu Mar 30 10:20:59 2017 From: ben.v.root at gmail.com (Benjamin Root) Date: Thu, 30 Mar 2017 10:20:59 -0400 Subject: [Matplotlib-users] segmentation fault problems with basemap In-Reply-To: References: Message-ID: Could you use the faulthandler package to help produce a stack trace? https://pypi.python.org/pypi/faulthandler/ If you are using python 3.4 or greater, it should already be in the standard library. Cheers! Ben Root On Wed, Mar 29, 2017 at 3:51 PM, Jason Snyder wrote: > Whenever I run a python with basemap I get a segmentation fault error. > For example when running: > from mpl_toolkits.basemap import Basemap > import matplotlib.pyplot as plt > # setup Lambert Conformal basemap. > # set resolution=None to skip processing of boundary datasets. > m = Basemap(width=12000000,height=9000000,projection='lcc', > resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) > # draw a land-sea mask for a map background. > # lakes=True means plot inland lakes with ocean color. > m.drawlsmask(land_color='coral',ocean_color='aqua',lakes=True) > plt.show() > > I get a segmentation fault core dump error. > > I have done some reading online about this and they say that it could be > because I accidently installed two versions of geos ( > http://trac.osgeo.org/geos/), which include geos.3.3.6 and geos.3.3.3 > which was already available in the basemap package. Could this be the > problem that is creating the segmentation fault core dump? If so how do I > uninstall the geos libraries that I do not need. There is not a lot of > specific information on how to uninstall geos libraries and I really need a > specific guide on how to do this and get the above script working properly. > > > > -- > Jason Snyder PhD > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmssnyder at ucdavis.edu Thu Mar 30 16:16:49 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Thu, 30 Mar 2017 20:16:49 +0000 Subject: [Matplotlib-users] plotting netcdf data on a map in matplotlib Message-ID: I am trying to plot data from a netcdf file onto a map through matplotlib. I initially tried to use basemap but then someone suggested that I use cartopy based on the website: http://scitools.org.uk/cartopy. Either way I am able to generate the map fine but am having difficulty plotting the data successfully. For instance using basemap I wind up getting a weird plot of data that does not make sense. Also how to I go about plotting the netcdf data around the dateline? Attached is the ncdump output (gridoutput.txt) for the netcdf file in terms of the grid and also the script that I am using to try to plot the data (netcdfplot.py). Can anyone give me some suggestions on how to go about fixing the errors that I have in the script? -Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- netcdf \2017032800 { dimensions: latitude = 159 ; longitude = 361 ; time = UNLIMITED ; // (1 currently) variables: double latitude(latitude) ; latitude:units = "degrees_north" ; latitude:long_name = "latitude" ; double longitude(longitude) ; longitude:units = "degrees_east" ; longitude:long_name = "longitude" ; double time(time) ; time:units = "seconds since 1970-01-01 00:00:00.0 0:00" ; time:long_name = "verification time generated by wgrib2 function verftime()" ; time:reference_time = 1490659200. ; time:reference_time_type = 1 ; time:reference_date = "2017.03.28 00:00:00 UTC" ; time:reference_time_description = "analyses, reference date is fixed" ; time:time_step_setting = "auto" ; time:time_step = 0. ; float HTSGW_surface(time, latitude, longitude) ; HTSGW_surface:_FillValue = 9.999e+20f ; HTSGW_surface:short_name = "HTSGW_surface" ; HTSGW_surface:long_name = "Significant Height of Combined Wind Waves and Swell" ; HTSGW_surface:level = "surface" ; HTSGW_surface:units = "m" ; // global attributes: :Conventions = "COARDS" ; :History = "created by wgrib2" ; :GRIB2_grid_template = 0 ; data: latitude = -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ; longitude = 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180 ; time = 1490659200 ; } -------------- next part -------------- A non-text attachment was scrubbed... Name: erroneous_chart.png Type: image/png Size: 17376 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: netcdfplot.py Type: text/x-python Size: 909 bytes Desc: not available URL: From jklymak at uvic.ca Thu Mar 30 16:38:19 2017 From: jklymak at uvic.ca (Jody Klymak) Date: Thu, 30 Mar 2017 13:38:19 -0700 Subject: [Matplotlib-users] plotting netcdf data on a map in matplotlib In-Reply-To: References: Message-ID: <4AB19189-5D29-4B14-A461-C587B4A52ECF@uvic.ca> I?m not an expert on cartopy. 1) can you plot this data w/o using basemap? 2) why do you have the ?squeeze? command in there? 3) I?m not clear what the problem is with your image from the snippet you sent. Is it just an issue with the longitude wrapping? Some projections demand longitude must be between -180 and 180. i.e. lon[lon>=180]=lon[lon>=180]-360. You may also need to re-order your longitude and data so that longitude is monotonically increasing. 4) I recommend xarray when dealing w/ netcdf files, though maybe that is overkill for your problem. A minimal working example with a link to the bad data always helps. I?m sure with a bit of experimentation and use of google you can get this working. i.e. http://stackoverflow.com/questions/13856123/setting-up-a-map-which-crosses-the-dateline-in-cartopy Cheers, Jody -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmssnyder at ucdavis.edu Thu Mar 30 16:49:11 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Thu, 30 Mar 2017 20:49:11 +0000 Subject: [Matplotlib-users] plotting netcdf data on a map in matplotlib In-Reply-To: <4AB19189-5D29-4B14-A461-C587B4A52ECF@uvic.ca> References: <4AB19189-5D29-4B14-A461-C587B4A52ECF@uvic.ca> Message-ID: The main issue I have is that the data does not plot properly. There evidently is an issue of matching coordinates in the data versus the map. I am sending the netcdf file along with the script. I am not sure how to plot a map with data without using basemap since this is what provides the continental outlines. If you know of any way I can plot this data using matplotlib successful let me know. -Jason On Thu, Mar 30, 2017 at 8:38 PM, Jody Klymak wrote: > I?m not an expert on cartopy. > > 1) can you plot this data w/o using basemap? > 2) why do you have the ?squeeze? command in there? > 3) I?m not clear what the problem is with your image from the snippet you > sent. Is it just an issue with the longitude wrapping? Some projections > demand longitude must be between -180 and 180. i.e. > lon[lon>=180]=lon[lon>=180]-360. You may also need to re-order your > longitude and data so that longitude is monotonically increasing. > 4) I recommend xarray when dealing w/ netcdf files, though maybe that is > overkill for your problem. > > A minimal working example with a link to the bad data always helps. > > I?m sure with a bit of experimentation and use of google you can get this > working. > > i.e. > http://stackoverflow.com/questions/13856123/setting-up- > a-map-which-crosses-the-dateline-in-cartopy > > Cheers, Jody > > > > > -- Jason Snyder PhD -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 2017032800.nc.tar.gz Type: application/x-gzip Size: 30496 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: testnetcdf.py Type: text/x-python Size: 28 bytes Desc: not available URL: From rmay31 at gmail.com Thu Mar 30 17:36:36 2017 From: rmay31 at gmail.com (Ryan May) Date: Thu, 30 Mar 2017 15:36:36 -0600 Subject: [Matplotlib-users] plotting netcdf data on a map in matplotlib In-Reply-To: References: <4AB19189-5D29-4B14-A461-C587B4A52ECF@uvic.ca> Message-ID: Here's a version that works for me with cartopy. It relies on np.roll(), which just got added in numpy 1.12, to correct the fact that the longitudes are arranged 180-360, 0-180, which seems to be causing problems. The other easy way to solve that is to plot the data in chunks. import cartopy.crs as ccrs import cartopy.feature as cfeat import matplotlib.pyplot as plt from netCDF4 import Dataset import numpy as np ncfile='/Users/rmay/Downloads/2017032800.nc' fh = Dataset(ncfile) lats = fh.variables['latitude'][:] lons = fh.variables['longitude'][:] HTSGW_var = fh.variables['HTSGW_surface'] roll_to = -lons.argmin() lons = np.roll(lons, roll_to) data = np.roll(HTSGW_var[:].squeeze(), roll_to, axis=-1) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_global() lon, lat = np.meshgrid(lons, lats) cs = ax.pcolor(lon, lat, data) # If roll not available #cs = ax.pcolor(lon[:, :180], lat[:, :180], data[:, :180]) #cs = ax.pcolor(lon[:, 180:], lat[:, 180:], data[:, 180:]) # draw coastlines. ax.coastlines() ax.add_feature(cfeat.LAND) plt.show() On Thu, Mar 30, 2017 at 2:49 PM, Jason Snyder wrote: > The main issue I have is that the data does not plot properly. There > evidently is an issue of matching coordinates in the data versus the map. > I am sending the netcdf file along with the script. I am not sure how to > plot a map with data without using basemap since this is what provides the > continental outlines. If you know of any way I can plot this data using > matplotlib successful let me know. > > -Jason > > > > On Thu, Mar 30, 2017 at 8:38 PM, Jody Klymak wrote: > >> I?m not an expert on cartopy. >> >> 1) can you plot this data w/o using basemap? >> 2) why do you have the ?squeeze? command in there? >> 3) I?m not clear what the problem is with your image from the snippet you >> sent. Is it just an issue with the longitude wrapping? Some projections >> demand longitude must be between -180 and 180. i.e. >> lon[lon>=180]=lon[lon>=180]-360. You may also need to re-order your >> longitude and data so that longitude is monotonically increasing. >> 4) I recommend xarray when dealing w/ netcdf files, though maybe that is >> overkill for your problem. >> >> A minimal working example with a link to the bad data always helps. >> >> I?m sure with a bit of experimentation and use of google you can get this >> working. >> >> i.e. >> http://stackoverflow.com/questions/13856123/setting-up-a- >> map-which-crosses-the-dateline-in-cartopy >> >> Cheers, Jody >> >> >> >> >> > > > -- > Jason Snyder PhD > > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at python.org > https://mail.python.org/mailman/listinfo/matplotlib-users > > -- Ryan May -------------- next part -------------- An HTML attachment was scrubbed... URL: