I hope this question isn't too elementary. I've searched extensively for a solution but haven't discovered one yet.
I've recently begun using Jupyter Notebook with Sympy to take notes and do my homework in my Calculus II class (and what a HUGE BENEFIT this has been!).
However, my sole problem with it is that I'm unable to figure out how to configure the size (i.e. the dimensions in pixels) of the plot figure.
It's easy enough to do using matplotlib directly (matplotlib.pyplot.figure() specifically), but I'm using the Sympy.mpmath.plotmodule because Sympy works much better for the symbolic manipulation we're doing in this course. I know Sympy has its own plotting module, but the one in mpmath seems easier to use so far (with the exception of this one issue, of course).
However, I've looked through the mpmath documentation and have googled the problem repeatedly, without a solution.
How can you change the size of the image that results from plotting a function using the mpmath API?
You may try changing the size of sympy's plots via pyplot's rcParams:
import sympy
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = 10, 3
sympy.mpmath.plot([cos, sin], [-4, 4])
Related
I am interested in porting some of my old fractal imaging programs over from Borland C to python. In Borland C, the putpixel command would place a specified color pixel within a rasterized graphical field. Is there a simple way to do this in matplotlib?
So the answer depends on what you're trying to do here. matplotlib has a lot of utilities for working with representing image data, this might give a good starting point for getting familiar with matplotlib's workflow. You can directly edit the values of the numpy array that you're using matplotlib to visualize, but matplotlib doesn't give you access to the data that you're rendering.
I imagine that you already have written some colormap and other rendering tools tools, but to get an idea of what matplotlib might have built in, I recommend looking at this example. It's a simple Mandelbrot, escape time, but it makes use of nonlinear colormapping and shading.
In my experience, I've normally computed the fractal as a 2D numpy array, and then allowed matplotlib to handle the coloring, and scaling of the final output image. Matplotlib doesn't work like the canvas experience it sounds like you're used to using. I'd recommend filling a numpy array with the desired pixel values as you've computed them, and then sending that array off to matplotlib to be rendered.
After posting this I discovered that there is a putpixel command in PIL (Python Imaging Library), which has tools for dealing with pixel oriented graphics. Matplotlib can also do the job as suggested by the answer above.
I am using interactive python with plt.ion() for generating figures (v2.7) and have noticed that the figure looks different from the figure exported by savefig (this is not a DPI issue (cf. matplotlib savefig() plots different from show()) - I think it might be a backend issue, but would appreciate help as I don't understand this properly).
Specifically, I wanted visualise the importance of a series of points by the intensity of their colour, which I thought I could do with the "alpha" keyword in matplotlib.
When I just do this, this works fine,
but when I want to add a line to the figure, the alpha keyword seemed to not work any more, and plt.ion() shows this:
I initially thought that perhaps the following issue on github may be related:
https://github.com/matplotlib/matplotlib/issues/4580
but then I noticed that exporting the figure actually produced the following file (i.e. as desired):
It would be great to understand a bit better what is going on, and how I can avoid such issues in the future. Is plt.ion()/plt.show() not the best way to show figures in interactive python, or is this an issue with the alpha keyword?
The code is here:
import numpy as np
from numpy import random as random
from matplotlib import pyplot as plt
fig2,ax2=plt.subplots(1,1,figsize=(3,3),sharey=True)
for ii in range(1):
ax2.plot(np.linspace(0,200,200), [0.1]*200, c= 'k')
for i in range(200):
test2=random.randint(5)
ydata= random.rand(test2)
test = random.rand(test2)
for j in range(test2):
ax2.plot(i,ydata[j],'o',ms=4, c= 'Darkblue',alpha=test[j],markeredgecolor='None')
I have written a python script to project and overlay geostationary satellite images from the university of Dundee so the resulting image can be used for xplanet to render the surface of the earth. The source code of the tool can be found at https://github.com/jmozmoz/cloudmap/tree/cartopy (this is the branch with cartopy support)
The tool support two different python libraries to project the geostationary images on a flat map: pyresample and cartopy.
I have found the following differences/problems:
pyresample is much faster than cartopy (depending on the size of the output image up to a factor of 10)
The output images differ: The results using pyresample show a stronger contrast.
For examples see the debug directory at https://github.com/jmozmoz/cloudmap/tree/cartopy/debug
If the multiprocessing library is used to do the projection in parallel, the cartopy version crashes with the following error message:
Fatal Python error: PyEval_RestoreThread: NULL tstate
So why is cartopy so much slower? Is pyresample doing the work in C code? Should cartopy support multiprocessing? And how to fix the problem with the contrast?
Thank you for your help
1. pyresample is much faster than cartopy (depending on the size of the output image up to a factor of 10)
The cartopy reprojection functionality hasn't been optimized in any way, and although it is using the scipy ckdtree functionality under the hood, the algorithm itself is written in Python. I seem to remember that a quick win was to use https://pypi.python.org/pypi/kdtree which from memory gave quite a reasonable speedup with little work, cartopy.img_transform would be the place where changes would be needed.
Cartopy's re-projection functionality is probably also paying the cost of being very general - you can provide an image in any projection, and it will put it into any other projection, dealing with discontinuities and tears without a problem. It would be really cool to hook into pyresample's functionality though (and GDAL's for that matter) to give users the opportunity to speed up the reprojection in certain cases.
2. The output images differ: The results using pyresample show a stronger contrast.
Looks like you're creating a matplotlib figure to resample the image and using mpl's savefig functionality. It is possible that this process is causing the contrast to be lost. I'd advise just using cartopy's reprojection functionality without adding an image to a figure and saving the figure (example at the end).
3. If the multiprocessing library is used to do the projection in parallel, the cartopy version crashes with the following error message:
This really surprised me as there is no C code in cartopy which is doing the reprojecting. Therefore you've either found a bug with scipy, or more likely you are hitting a problem with numpy/matplotlib (google brings up a few results with your exception and matplotlib and/or numpy, e.g. https://github.com/numpy/numpy/issues/1270).
Ok, so here is how I would do the reprojection without using matplotlib at all:
import cartopy.crs as ccrs
from cartopy.img_transform import warp_array
import numpy as np
import PIL.Image
# I've downloaded the file from https://github.com/jmozmoz/cloudmap/blob/78923d15ad906eaa6d1dcab168a6364643d3fc94/debug/2014_8_7_1800_GOES15_4_S1.jpeg
# and clipped the image.
fname = '2014_8_7_1800_GOES15_4_S1.jpeg'
img = PIL.Image.open(fname)
result_array, extent = warp_array(np.array(img),
source_proj=ccrs.Geostationary(),
target_proj=ccrs.PlateCarree(),
target_res=(4000, 2000))
result = PIL.Image.fromarray(result_array)
result.save('reprojected.jpeg')
With the resulting image (eventually) looking something like:
There are some real possibilities for some optimisations with this functionality - quite a large amount of work is done creating the kdtree in the first place (which could potentially be cached) and another large chunk of the work is computing the indices from the original image (again, caches very well) which would essentially reduce and repeat reprojections to an numpy indexing problem.
If you want to look into the performance possibilities or the contrast issue (which I'm uncertain whether my solution fixes or not) please feel free to open up an issue on the github repo and we can talk through some of the options.
Thanks for asking, and HTH!
Since some years ago I use matlab for my plots (mostly density plots), but now I want to change to matplotlib. I have a problem trying to figure out how to get analogous plots in matplotlib. I have to represent a 2D array. In matlab I used to use the surf function, and then change to view(2) (az=0 and el=90). An example:
surf(X,Y,log10(z),'FaceColor','interp','EdgeColor','none')
view(2)
In matplotlib I have tried some functions, but I have not got the same feeling. m3plot is a computationally expensive toolkit and it is not the same as using surf. imshow does not allow to use log functions in his arguments (like the example), and log values is something mandatory for me. Then it is pcolor, but I can not find a 'FaceColor'-like option to smooth the edges. I would like to know if someone knows what is the best equivalent in matplotlib.
Thank you for your time!
Try installing mayavi which has the surf function (mayavi is a fully-blown 3D visualisation library using hardware acceleration)
Finally, the solution that suits me is to use the routine pcolormesh(). This combined with the option shading='gouraud' interpolates the data and smooth the edges. In addition, it works pretty well with large arrays in comparision with pcolor.
This question already has answers here:
Which is the recommended way to plot: matplotlib or pylab?
(2 answers)
Closed 1 year ago.
What is the difference between
matplotlib.pyplot and matplotlib.pylab?
Which is preferred for what usage?
I am a little confused, because it seems like independent from which I import, I can do the same things. What am I missing?
This wording is no longer in the documentation.
Use of the pylab import is now discouraged and the OO interface is recommended for most non-interactive usage.
From the documentation, the emphasis is mine:
Matplotlib is the whole package; pylab is a module in matplotlib that gets installed alongside matplotlib; and matplotlib.pyplot is a module in matplotlib.
Pyplot provides the state-machine interface to the underlying plotting library in matplotlib. This means that figures and axes are implicitly and automatically created to achieve the desired plot. For example, calling plot from pyplot will automatically create the necessary figure and axes to achieve the desired plot. Setting a title will then automatically set that title to the current axes object:
Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace, making that namespace (or environment) even more MATLAB-like. For example, one can call the sin and cos functions just like you could in MATLAB, as well as having all the features of pyplot.
The pyplot interface is generally preferred for non-interactive plotting (i.e., scripting). The pylab interface is convenient for interactive calculations and plotting, as it minimizes typing. Note that this is what you get if you use the ipython shell with the -pylab option, which imports everything from pylab and makes plotting fully interactive.