This question already has answers here:
How do I make a single legend for many subplots?
(10 answers)
How to put the legend outside the plot
(18 answers)
Closed 6 months ago.
I've created a plot with two axes and one legend containing every line regardless of its axis.
I want to use the parameter <loc="best"> which works for all lines in axis 1. I also want it to work with axis 2. Any ideas?
My code:
lns = self.ln1 + self.ln2 + self.ln3
labels = [l.get_label() for l in lns]
self.ax1.legend(lns, labels, loc="best")
As I assign one legend only to axis one, the loc parameter also only applies to axis one. How can I change this so I still only have one legend but the loc parameter works with all axes.
This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 3 years ago.
I have the following code:
def compare(f,a,b,c,d,n,points):
"""Plots 2 figures - one of the color map of f, and one of the color map of a rectangle [a,b] x [c,d], split
into n^2 subareas, using the list of points to estimate the color map"""
#fig, axes = plt.subplots(nrows=2, ncols=2)
q = plt.figure(1)
colorMapList(f,a,b,c,d,n,points)
#q.show()
p = plt.figure(2)
colorMap(f)
plt.show()
The functions colorMapList and colorMap both return ax.contourf(Y,X,z).
When I have the code the way I have it, the program outputs two diagrams, one below the other. How can I have it so that the diagrams are displayed horizontally next to each other?
Thanks!
If you want both graphs on a single figure then you can use plt.subplot(121) and plt.subplot(122). The first index is the number of rows and the second index is the number of cols. The third index is the position count of the figure layout, so if it was subplot(221) would be a 2x2 display of graphs and the 1 represents the graph in the upper left. Then, subplot(222) would be upper right, subplot(223) is bottom left, and subplot(224) is bottom right. This follow the sequence from top left to right for each row.
However, if you want to plot 2 different figures that are side-by-side then you can look at this solution.
This question already has answers here:
How to set some xlim and ylim in Seaborn lmplot facetgrid
(2 answers)
Closed 4 years ago.
Most seaborn plotting functions (e.g. seaborn.barplot, seaborn.regplot) return a matplotlib.pyplot.axes when called, so that you can use this object to further customize the plot as you see fit.
However, I wanted to create an seaborn.lmplot, which doesn't return the axes object. After digging through the documentation of both seaborn.lmplot and seaborn.FacetGrid (which lmplot uses in it's backend), I found no way of accessing the underlying axes objects. Moreover, while most other seaborn functions allow you to pass your own axes as a parameter on which they will draw the plot on, lmplot doesn't.
One thing I thought of is using plt.gca(), but that only returns the last axes object of the grid.
Is there any way of accessing the axes objects in seaborn.lmplot or seaborn.FacetGrid?
Yes, you can access the matplotlib.pyplot.axes object like this:
import seaborn as sns
lm = sns.lmplot(...) # draw a grid of plots
ax = lm.axes # access a grid of 'axes' objects
Here, ax is an array containing all axes objects in the subplot. You can access each one like this:
ax.shape # see the shape of the array containing the 'axes' objects
ax[0, 0] # the top-left (first) subplot
ax[i, j] # the subplot on the i-th row of the j-th column
If there is only one subplot you can either access it as I showed above (with ax[0, 0]) or as you said in your question through (plt.gca())
This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 4 years ago.
I have several histograms that I want to include in a single figure. I know I can do this:
plt.title("Mondays")
plt.hist(mon["price"], bins=50, alpha=0.5, histtype='bar', ec='black')
plt.show()
But if I add another plt.hist(...) before calling plt.show(), matplotlib adds the second histogram on top of the first one. I'd like separate subplots for each of mon["price"], tues["price"], ..., sun["price"].
How would I go about that?
You can use subplots as in this example: matplotlob documentation 2 plots
plt.subplot(211) means: 2 rows, 1 column, 1:this is the 1st plot.
Here is an example with 4 plots: 2 rows and 2 columns:
4 plots
I have written code that opens 16 figures at once. Currently, they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Furthermore, for some reason, the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do?
import csv
import scipy.stats
import numpy
import matplotlib.pyplot as plt
for i in range(16):
plt.figure(i)
filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\')
alt_file=open(filename)
a=[]
for row in csv.DictReader(alt_file):
a.append(row['Dist_90m(nmi)'])
y= numpy.array(a, float)
relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60))
bins = numpy.arange(-10,60,10)
print numpy.sum(relpdf[0])
print bins
patches=plt.bar(bins,relpdf[0], width=10, facecolor='black')
titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None)
plt.title(titlename)
plt.ylabel('Probability Density Function')
plt.xlabel('Distance from 90m Contour Line(nm)')
plt.ylim([0,1])
plt.show()
The answer from las3rjock, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.
Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order.
First, calling subplot does not give you multiple plots; subplot is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.
plt.figure() (in which plt or PLT is usually matplotlib's pyplot library imported and rebound as a global variable, plt or sometimes PLT, like so:
from matplotlib import pyplot as PLT
fig = PLT.figure()
the line just above creates a matplotlib figure instance; this object's add_subplot method is then called for every plotting window (informally think of an x & y axis comprising a single subplot). You create (whether just one or for several on a page), like so
fig.add_subplot(111)
this syntax is equivalent to
fig.add_subplot(1,1,1)
choose the one that makes sense to you.
Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to add_subplot. Notice the argument is (211) for the first plot and (212) for the second.
from matplotlib import pyplot as PLT
fig = PLT.figure()
ax1 = fig.add_subplot(211)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])
ax2 = fig.add_subplot(212)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])
PLT.show()
Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.
211 (which again, could also be written in 3-tuple form as (2,1,1) means two rows and one column of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.
The argument passed to the second call to add_subplot, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).
An example with more plots: if instead you wanted four plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.
Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.
The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).
Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots which is very convenient:
fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
where axes is a numpy.ndarray of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j].
To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.
This works also:
for i in range(19):
plt.subplot(5,4,i+1)
It plots 19 total graphs on one page. The format is 5 down and 4 across..
#doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.
import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:
ax=plt.subplot(2,1,i+1)
df[[i]].plot(ax=ax)
print(i)
plt.show()
For example, to create 6 subplots with 2 rows and 3 columns you can use:
funcs = [np.cos, np.sin, np.tan, np.arctan]
x = np.linspace(0, 10, 100)
fig = plt.figure(figsize=(10, 5))
for num, func in enumerate(funcs, start=1):
ax = fig.add_subplot(2, 2, num) # plot with 2 rows and 2 columns
ax.plot(x, func(x))
ax.set_title(func.__name__)
# add spacing between subplots
fig.tight_layout()
Result: