I often plot a point on a matplotlib plot with:
x = 10
y = 100
plot(x, y, "k*", label="Global Optimum")
legend()
However, this causes the legend to put a star in the legend twice, such that it looks like:
* * Global Optimum
when I really want it to look like:
* Global Optimum
How do I do this?
This should work:
legend(numpoints=1)
BTW, if you add the line
legend.numpoints : 1 # the number of points in the legend line
to your matplotlibrc file, then this will be the new default.
[See also scatterpoints, depending on your plot.]
API: Link to API docs
I like to change my matplotlib rc parameters dynamically in every python script. To achieve this goal I simply use somthing like that at the beginning of my python files.
from pylab import *
rcParams['legend.numpoints'] = 1
This will apply to all plots generated from my python file.
EDIT: For those who do not like to import pylab, the long answer is
import matplotlib as mpl
mpl.rcParams['legend.numpoints'] = 1
Related
from matplotlib.pyplot import *
list = [1,3,5,7,2,4,6,8,10]
plot(list)
With my code above, the code will graph with x-axis run from 0 to 8. What should I do if I want my x-axis run from another value? i.e. my x-axis run from 120-128?
You can just use the show() function to show the graph.
Your code should look something like this.
from matplotlib.pyplot import *
list = [1,3,5,7,2,4,6,8,10]
plot(list)
show()
And also, as mentioned in the comments by #BcK, don't use keywords or in-built function names as variable names, finally don't import * , this is not a good practice. You can update your whole program to this:
import matplotlib.pyplot as plt
var_list = [1,3,5,7,2,4,6,8,10] # don't use keywords or inbuilt function names as varible names
plt.plot(var_list)
plt.show() # this is to visualize the plot
My question is not about matplotlib in detail, but a general programming and question, and i'm looking for an answer on the mechanisms making this possible in python or matplotlib core.
Let's say I have a scatter plot using the code:
import matplotlib.pyplot as plt
plt.scatter(a,b)
plt.show()
I'm wondering how is this statement handled?
How does python (or matplotlib?) know what to plot and where to get the data?
How are these statement handled by interpreter?
Maybe I finally see the point of this question. Of course we cannot explain pyplot here, because that is much too complicated and would require a complete tutorial (which btw do exist). But we can have a look at how pyplot would work as a module in a very simplified manner.
So let's create myplot, the ultimative console plotting library. ;-)
The module myplot could look as follows. It has two functions, scatter and show and two variables, figures and plot. plot would store our coordinate system to plot to. figures would store the figures we create.
plot = """
^
|
|
|
|
|
+----------->"""
figures = []
def scatter(X,Y):
thisplot = list(plot[:])
for x,y in zip(X,Y):
thisplot[1+14*(6-y)+x] = "*"
thisplot = "".join(thisplot)
figures.append(thisplot)
def show():
for fig in figures:
print(fig)
Calling scatter creates a new figure from plot and stores it in the figures list. Calling show takes all figures from that list, and shows them (prints them in the console).
So using myplot would look exactly like the example above.
import myplot as mlt
mlt.scatter([2,3,4,5,6,8],[2,5,4,4,3,2])
mlt.show()
Creating the output:
^
| *
| **
| *
| * *
|
+----------->
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()
I will not be able to put the code here because it is my assignment.
My program is printing multiple graphs on one plot. Please look at the example figure on the following link: Python: Plot multiple graphs on the same figure
The link above is just an example. That is not my code nor do I have the same program. My topic is completely different. That figure is just for reference.
The line of code I am using to achieve this is: plot(a,b, label=str(meters))
What I want to do is get any one of those graph from those three curves and also plot it separately as if it is the main graph. I am doing all this inside a function, and I have created an array of numbers to loop through these different values to get three different graphs.
Do you mean something like this?
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
a = np.arange(5)
line1, = plt.plot(a, a**2) # a new figure instance is opened automatically
line2, = plt.plot(a, a**3-a)
line3, = plt.plot(a, 4*a-a**2/2.)
fig_handle = plt.figure() # Force a new figure instance to open
plt.plot(a, a**2) # This will replot 'line1', but in this new figure instance.
If not, please update your question, perhaps showing the code you already have.
Note that this is information you could find on the matplotlib pyplot tutorial.
Assume that I have some data, and I want to create a plot of this data by passing it to a custom plotting function (myplot()). I am using the matplotlib's modules in myplot().
I would like myplot() to return the handle to a figure, and not plot display the plot when I call this function. Here is a sample code and output from iPython.
I have two questions regarding this:
Why do I still see a plot, even though I am assigning the output of
myplot() to f?
What do I need to supress this plot when I am assigning the output of myplot() to a variable?
Start ipython with
ipython notebook
rather than
ipython notebook --pylab=inline
If you do not want to start the whole notebook in non-inline-modus you can just use the following code:
%config InlineBackend.close_figures = False
def myplot(t,x):
fig = figure()
x = plot(t,x)
fig.savefig('plot.png') # This is just to show the figure is still generated
return fig
t = arange(0,6,0.01)
x = sin(t)
f = myplot(t,x)