Writing astronomical units in the labels of plot - python

I use matplotlib to plot my data but I need to write in labels the unit and I it doesn't work the way it works in latex. For instance in latex by using siunitx package then I can write \arcsecond unit but how should it be done in matplotlib?

You can do it like this:
import pylab as plt
from matplotlib.ticker import FormatStrFormatter
x = range(10)
plt.plot(x)
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d unit'))

Related

How can I make a scatter plot using proplot? (Python)

I just downloaded the ProPlot package and am wondering how I can make a scatter plot. I looked into this example, but as I tried
import proplot as plt
plt.figure(...)
plt.scatter(...)
it returns me AttributeError: module 'proplot' has no attribute 'scatter' . My plot worked when I did
import proplot as plt
import matplotlib.pyplot as plt
plt.figure(...)
plt.scatter(...)
And I did see the effect of proplot in this way. However, I don't think it's right to import two packages with the same notation plt. Is there a better way I can generate the scatter plot using proplot? Thanks!
Proplot does not offer a direct replacement for the scatter plot at the top level of the proplot module. The only way to construct it is to call the method of an axis object:
import proplot as pplt
fig, ax = pplt.subplots()
ax.scatter()
Or alternatively:
fig = pplt.figure()
ax = fig.subplot()
ax.scatter(...)
Note that if you import matplotlib after proplot under the same name plt alias, you won't be able to use the proplot interface under plt since it'll be replaced by matplotlib. It is not "wrong" to do so, since it is legal python, but surely not what you intended to accomplish.

Figure not displayed with matplotlib.use('Agg')

I work with matplotlib. When I add the following lines, the figure is not displayed.
import matplotlib
matplotlib.use('Agg')
here is my code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plot.figure(figsize=(12,9))
def convert_sin_cos(x):
fft_axes = fig.add_subplot(331)
y = np.cos(x)
fft_axes.plot(x,y,'g*')
for i in range(3):
fft_axes = fig.add_subplot(332)
x=np.linspace(0,10,100)
fft_axes.plot(x,i*np.sin(x),'r+')
plot.pause(0.1)
convert_sin_cos(x)
Thanks
That's the idea!
When I run your code, the console says:
matplotlibAgg.py:15: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
How can it be useful? When you're running matplotlib code in a terminal with no windowing system, for example: a cluster (running the same code with different inputs, getting lot of results and without the need to move the data I can plot whatever I need).

What is the preferred way to import pylab at a function level in Python 2.7?

I have written a relatively simple function in python that can be used to plot the time domain history of a data set as well as the frequency domain response of a data set after a fast fourier transform. In this function I use the command from pylab import * to bring in all the necessary functionality. However, despite successfully creating the plot, I get a warning stating
import * only allowed at the module level.
So if using the command from pylab import * is not the preferred methodology, how do I properly load all the necessary functionality from pylab. The code is attached below. Also, is there a way to close the figure after the function is exited, I have tried plt.close() which is not recognized for subplots?
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
from pylab import *
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,plt = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
plt.set_xlabel(X_Label,fontsize=18)
plt.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
fig.savefig(Output_Location)
plt.clear()
From the matplotlib documentation:
pylab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and numpy (for mathematics and working with arrays) in a single name space. Although many examples use pylab, it is no longer recommended.
I would recommend not importing pylab at all, and instead try using
import matplotlib
import matplotlib.pyplot as plt
And then prefixing all of your pyplot functions with plt.
I also noticed that you assign the second return value from plt.subplots() to plt. You should rename that variable to something like fft_plot (for fast fourier transform) to avoid naming conflicts with pyplot.
With regards to your other question (about fig, save fig()) you're going to need to drop that first fig because it's not necessary, and you'll call savefig() with plt.savefig() because it is a function in the pyplot module. So that line will look like
plt.savefig(Output_Location)
Try something like this:
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
import matplotlib
from matplotlib import rcParams, pyplot as plt
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,fft_plot = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
fft_plot.set_xlabel(X_Label,fontsize=18)
fft_plot.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
plt.savefig(Output_Location)
plt.close()

Is there any way to ask Basemap not show the plot?

I am trying to use mpl_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen.
My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X Display, is $DISPLAY set properly?'
Is there any way I can avoid the plot to be shown when I use a Basemap function on it?
I just want to save it to a file so later I can read it externally.
My code is:
from mpl_toolkits.basemap import Basemap
import numpy as np
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))
Use the Agg backend, it doesn't require a graphical environment:
Do this at the very beginning of your script:
import matplotlib as mpl
mpl.use('Agg')
See also the FAQ on Generate images without having a window appear.
The easiest way is to put off the interactive mode of matplotlib.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
#NOT SHOW
plt.ioff()
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))

Python: saving a plot and not opening it in a GUI

I'm trying to run a little program that should save my 3D scatterplot instead of opening it in a GUI. The problem is that it does both! This is the piece of code I'm talking about:
from matplotlib import pyplot
from scipy import math
from mpl_toolkits.mplot3d import Axes3D
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xPosition, yPosition, zPosition, c = velocity, s = mass)
ax.set_xlim3d(-plotSize, plotSize)
ax.set_ylim3d(-plotSize, plotSize)
ax.set_zlim3d(-plotSize, plotSize)
pyplot.savefig('plot.png')
I would very much like to know how I can get a saved image of my plot without the plot being opened in a gui.
You should use pylab.ioff() as hilghlight by Saullo Castro, and each time you want to save a figure use pylab.savefig('file.png'). When you don't need the figure just do a pylab.close() to close the current figure (and free memory).
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
pyplot.ioff()
fig = pyplot.figure()
# HERE your code to add things in the figure
pyplot.savefig('file.png')
pyplot.close()

Categories

Resources