How to adjust and shape the subplots? - python

I am trying to plot 2 plots in one figure. So just 2 subplots and adjust the figure sizes and find a decent one. At the moment I am using this code:
import matplotlib.pyplot as plt
import pandas as pd
#import numpy as np
##### import data #####
df=pd.read_csv('C:\\Users\Kevin\Documents\Afstudeer\Measurements/1st_plot.txt',sep=',',decimal='.',header=None)
df.columns=['Vx','Vy','undefined','Laser_signal']
fig, ax = plt.subplots(figsize=(8, 5))
ax1=fig.add_subplot(121)
ax1.plot(df['Vx'],df['Vy'],label='plot')
plt.xlabel(r'$V_x$')
plt.ylabel(r'$V_y$')
ax2=fig.add_subplot(122)
ax1.scatter(df['Vx'],df['Vy'],label='data_points')
plt.xlabel(r'$V_x$')
plt.ylabel(r'$V_y$')
plt.subplots_adjust(left=.2, bottom=.45, right=.8, top=.95,
wspace=.3, hspace=.4)
so its this last code that is confusing me. When i do the plot, i get something like this:
Here is my sample data:
-1.725953467,0.109343505,-10.433363664,0.159675246
-1.725953467,0.110607445,-10.433363664,0.159675246
-1.729140157,0.110607445,-10.433363664,0.159675246
-1.722766777,0.10839555,-10.433363664,0.159675246
-1.727865481,0.11534722,-10.433363664,0.159359499
-1.726272136,0.112503355,-10.433363664,0.159675246
-1.731689509,0.120086995,-10.433363664,0.159359499
-1.727228143,0.117559115,-10.433363664,0.159359499
-1.729140157,0.11977101,-10.433363664,0.159675246
-1.730096164,0.121350935,-10.433363664,0.159675246
-1.729458826,0.122614875,-10.433363664,0.159043752
-1.735832206,0.12482677,-10.433363664,0.159359499
-1.728821488,0.121350935,-10.433363664,0.159675246
-1.733920192,0.124510785,-10.433363664,0.159359499
-1.731052171,0.12166692,-10.433363664,0.159675246
-1.739018896,0.12735465,-10.433363664,0.159043752
-1.738062889,0.12861859,-10.433363664,0.159043752
-1.738700227,0.133358365,-10.433363664,0.159043752
-1.73455753,0.12988253,-10.433363664,0.159043752
-1.743161593,0.144101855,-10.433363664,0.159043752
As you will see from the code, I am only taking the 1st 2 columns. I am expecting 2 subplots in a one figure. So why do i get these up and bottom lines between the plots??

The two lines
fig, ax = plt.subplots(figsize=(8, 5))
ax1=fig.add_subplot(121)
are somehow mutually exclusive. Either you create the subplots via
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 5))
or you create them via
fig = plt.figure()
ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)
After that better use the axes handles ax1 and ax2 to set any properties, e.g.
ax1.set_xlabel(r'$V_x$')
instead of plt.xlabel.

Related

set xlim across multiple figures in python? [duplicate]

I'm trying to share two subplots axes, but I need to share the x axis after the figure was created. E.g. I create this figure:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig = plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)
# some code to share both x axes
plt.show()
Instead of the comment I want to insert some code to share both x axes.
How do I do this? There are some relevant sounding attributes
_shared_x_axes and _shared_x_axes when I check to figure axis (fig.get_axes()) but I don't know how to link them.
The usual way to share axes is to create the shared properties at creation. Either
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
or
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
Sharing the axes after they have been created should therefore not be necessary.
However if for any reason, you need to share axes after they have been created (actually, using a different library which creates some subplots, like here might be a reason), there would still be a solution:
Using
ax1.get_shared_x_axes().join(ax1, ax2)
creates a link between the two axes, ax1 and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted).
A complete example:
import numpy as np
import matplotlib.pyplot as plt
t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
ax1.plot(t,x)
ax2.plot(t,y)
ax1.get_shared_x_axes().join(ax1, ax2)
ax1.set_xticklabels([])
# ax2.autoscale() ## call autoscale if needed
plt.show()
The other answer has code for dealing with a list of axes:
axes[0].get_shared_x_axes().join(axes[0], *axes[1:])
As of Matplotlib v3.3 there now exist Axes.sharex, Axes.sharey methods:
ax1.sharex(ax2)
ax1.sharey(ax3)
Just to add to ImportanceOfBeingErnest's answer above:
If you have an entire list of axes objects, you can pass them all at once and have their axes shared by unpacking the list like so:
ax_list = [ax1, ax2, ... axn] #< your axes objects
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list)
The above will link all of them together. Of course, you can get creative and sub-set your list to link only some of them.
Note:
In order to have all axes linked together, you do have to include the first element of the axes_list in the call, despite the fact that you are invoking .get_shared_x_axes() on the first element to start with!
So doing this, which would certainly appear logical:
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list[1:])
... will result in linking all axes objects together except the first one, which will remain entirely independent from the others.

Add multiple axes from different sources into same figure

I am using Python/matplotlib to create a figure whereby it has three subplots, each returned from a different 'source' or class method.
For example, I have a script called 'plot_spectra.py' that contains the Spectra() class with method Plot().
So, calling Spectra('filename.ext').Plot() will return a tuple, as per the code below:
# create the plot
fig, ax = plt.subplots()
ax.contour(xx, yy, plane, levels=cl, cmap=cmap)
ax.set_xlim(ppm_1h_0, ppm_1h_1)
ax.set_ylim(ppm_13c_0, ppm_13c_1)
# return the contour plot
return fig, ax
It is my understanding that the 'figure' is the 'window' in matplotlib, and the 'ax' is an individual plot. I would then want to say, plot three of these 'ax' objects in the same figure, but I am struggling to do so because I keep getting an empty window and I think I have misunderstood what each object actually is.
Calling:
hnca, hnca_ax = Spectra('data/HNCA.ucsf', type='sparky').Plot(plane_ppm=resi.N(), vline=resi.H())
plt.subplot(2,2,1)
plt.subplot(hnca_ax)
eucplot, barplot = PlotEucXYIntensity(scores, x='H', y='N')
plt.subplot(2,2,3)
plt.subplot(eucplot)
plt.subplot(2,2,4)
plt.subplot(barplot)
plt.show()
Ultimately, what I am trying to obtain is a single window that looks like this:
Where each plot has been returned from a different function or class method.
What 'object' do I need to return from my functions? And how do I incorporate these three objects into a single figure?
I would suggest this kind of approach, where you specify the ax on which you want to plot in the function:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def Spectra(data, ax):
ax.plot(data)
def PlotIntensity(data, ax):
ax.hist(data)
def SeabornScatter(data, ax):
sns.scatterplot(data, data, ax = ax)
spectrum = np.random.random((1000,))
plt.figure()
ax1 = plt.subplot(1,3,1)
Spectra(spectrum, ax1)
ax2 = plt.subplot(1,3,2)
SeabornScatter(spectrum, ax2)
ax3 = plt.subplot(1,3,3)
PlotIntensity(spectrum, ax3)
plt.tight_layout()
plt.show()
You can specify the grid for the subplots in very different ways, and you probably also want to have a look on the gridspec module.
One way to do this is:
f = plt.figure()
gs = f.add_gridspec(2,2)
ax = f.add_subplot(gs[0,:])
Think of the '2,2' as adding 2 row x 2 columns.
On the third line 'gs[0,:]' is telling to add a chart on row 0, all columns. This will create the chart on the top of your top. Note that indices begin with 0 and not with 1.
To add the 'eucplot' you will have to call a different ax on row 1 and column 0:
ax2 = f.add_subplot(gs[1,0])
Lastly, the 'barplot' will go in yet a different ax on row 1, column 1:
ax3 = f.add_subplot(gs[1,1])
See this site here for further reference: Customizing Figure Layouts Using GridSpec and Other Functions

Adjusting the x-axis label for multiple subplots [duplicate]

I'm trying to share two subplots axes, but I need to share the x axis after the figure was created. E.g. I create this figure:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig = plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)
# some code to share both x axes
plt.show()
Instead of the comment I want to insert some code to share both x axes.
How do I do this? There are some relevant sounding attributes
_shared_x_axes and _shared_x_axes when I check to figure axis (fig.get_axes()) but I don't know how to link them.
The usual way to share axes is to create the shared properties at creation. Either
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
or
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
Sharing the axes after they have been created should therefore not be necessary.
However if for any reason, you need to share axes after they have been created (actually, using a different library which creates some subplots, like here might be a reason), there would still be a solution:
Using
ax1.get_shared_x_axes().join(ax1, ax2)
creates a link between the two axes, ax1 and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted).
A complete example:
import numpy as np
import matplotlib.pyplot as plt
t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
ax1.plot(t,x)
ax2.plot(t,y)
ax1.get_shared_x_axes().join(ax1, ax2)
ax1.set_xticklabels([])
# ax2.autoscale() ## call autoscale if needed
plt.show()
The other answer has code for dealing with a list of axes:
axes[0].get_shared_x_axes().join(axes[0], *axes[1:])
As of Matplotlib v3.3 there now exist Axes.sharex, Axes.sharey methods:
ax1.sharex(ax2)
ax1.sharey(ax3)
Just to add to ImportanceOfBeingErnest's answer above:
If you have an entire list of axes objects, you can pass them all at once and have their axes shared by unpacking the list like so:
ax_list = [ax1, ax2, ... axn] #< your axes objects
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list)
The above will link all of them together. Of course, you can get creative and sub-set your list to link only some of them.
Note:
In order to have all axes linked together, you do have to include the first element of the axes_list in the call, despite the fact that you are invoking .get_shared_x_axes() on the first element to start with!
So doing this, which would certainly appear logical:
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list[1:])
... will result in linking all axes objects together except the first one, which will remain entirely independent from the others.

How to unset `sharex` or `sharey` from two axes in Matplotlib

I have a series of subplots, and I want them to share x and y axis in all but 2 subplots (on a per-row basis).
I know that it is possible to create all subplots separately and then add the sharex/sharey functionality afterward.
However, this is a lot of code, given that I have to do this for most subplots.
A more efficient way would be to create all subplots with the desired sharex/sharey properties, e.g.:
import matplotlib.pyplot as plt
fix, axs = plt.subplots(2, 10, sharex='row', sharey='row', squeeze=False)
and then set unset the sharex/sharey functionality, which could hypothetically work like:
axs[0, 9].sharex = False
axs[1, 9].sharey = False
The above does not work, but is there any way to obtain this?
As #zan points out in the their answer, you can use ax.get_shared_x_axes() to obtain a Grouper object that contains all the linked axes, and then .remove any axes from this Grouper. The problem is (as #WMiller points out) that the ticker is still the same for all axes.
So one will need to
remove the axes from the grouper
set a new Ticker with the respective new locator and formatter
Complete example
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(3, 4, sharex='row', sharey='row', squeeze=False)
data = np.random.rand(20, 2, 10)
for ax in axes.flatten()[:-1]:
ax.plot(*np.random.randn(2,10), marker="o", ls="")
# Now remove axes[1,5] from the grouper for xaxis
axes[2,3].get_shared_x_axes().remove(axes[2,3])
# Create and assign new ticker
xticker = matplotlib.axis.Ticker()
axes[2,3].xaxis.major = xticker
# The new ticker needs new locator and formatters
xloc = matplotlib.ticker.AutoLocator()
xfmt = matplotlib.ticker.ScalarFormatter()
axes[2,3].xaxis.set_major_locator(xloc)
axes[2,3].xaxis.set_major_formatter(xfmt)
# Now plot to the "ungrouped" axes
axes[2,3].plot(np.random.randn(10)*100+100, np.linspace(-3,3,10),
marker="o", ls="", color="red")
plt.show()
Note that in the above I only changed the ticker for the x axis and also only for the major ticks. You would need to do the same for the y axis and also for minor ticks in case it's needed.
You can use ax.get_shared_x_axes() to get a Grouper object that contains all the linked axes. Then use group.remove(ax) to remove the specified axis from that group. You can also group.join(ax1, ax2) to add a new share.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 10, sharex='row', sharey='row', squeeze=False)
data = np.random.rand(20, 2, 10)
for row in [0,1]:
for col in range(10):
n = col*(row+1)
ax[row, col].plot(data[n,0], data[n,1], '.')
a19 = ax[1,9]
shax = a19.get_shared_x_axes()
shay = a19.get_shared_y_axes()
shax.remove(a19)
shay.remove(a19)
a19.clear()
d19 = data[-1] * 5
a19.plot(d19[0], d19[1], 'r.')
plt.show()
This still needs a little tweaking to set the ticks, but the bottom-right plot now has its own limits.
You can access the group of shared axes using either ax.get_shared_x_axes() or by the property ax._shared_y_axes. You can then reset the visibility of the labels using xaxis.set_tick_params(which='both', labelleft=True) or using setp(ax, get_xticklabels(), visible=True) however both of these methods suffer from the same innate problem: the tick formatter is still shared between the axes. As far as I know there is no way around this. Here is an example to demonstrate:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
fig, axs = plt.subplots(2, 2, sharex='row', sharey='row', squeeze=False)
axs[0][0]._shared_x_axes.remove(axs[0][0])
axs[0][0]._shared_y_axes.remove(axs[0][0])
for ii in range(2):
for jj in range(2):
axs[ii][jj].plot(np.random.randn(100), np.linspace(0,ii+jj+1, 100))
axs[0][1].yaxis.set_tick_params(which='both', labelleft=True)
axs[0][1].set_yticks(np.linspace(0,2,7))
plt.show()

how to plot histogram and time series in python

I have two different pandas dataframes from which I obtained the following graphs:
ar_month_mean.plot(figsize=(15,5))
hist_month.plot(kind='bar', figsize=(15,5))
I'd like to combine them to obtain something similar to this:
you can pass an ax to the plotting methods, to have multiple plots in the same ax. Otherwise, each new plot will be in a new axis:
import matplotlib.pyplot as plt
f = plt.figure(figsize=(15,5))
ax = plt.gca()
ar_month_mean.plot(ax=ax, figsize=(15,5))
hist_month.plot(ax=ax, kind='bar', figsize=(15,5))
If you post the actually data, I will upload the resulting figure.

Categories