How to get two subplots side-by-side in matplotlib? - python

I just used following code to plot 2 subplot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar')
ax2 = fig.add_subplot(122)
temp2.plot(kind='bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
I am getting following output
I am getting 3 plots i.e. 2 subplots as I intended, however the second one empty with titles as described. And third one underneath the two with bars for temp2 without the titles.
What I want are two subplots side by side with titles as described. Wondering what I have done wrong?

I'm not able to reproduce this exactly unless I put plt.show() between creating the second axes instance and temp2.plot(kind='bar'). If you aren't calling plt.show() (or clearing the buffer in some other way) you should try
temp1.plot(kind='bar', ax=ax1)
temp2.plot(kind='bar', ax=ax2)
This should correctly use the two generated axes instances.

Related

Problems with plt.subplots, which should be the best option?

I'm new in both python and stackoverflow... I come from the ggplot2 R background and I am still getting stacked with python. I don't understand why I have a null plot before my figure using matplotlib... I just have a basic pandas series and I want to plot some of the rows in a subplot, and some on the others (however my display is terrible and I don't know why/how to fix it). Thank you in advance!
df = organism_df.T
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize=(5,5))
ax1 = df.iloc[[0,2,3,-1]].plot(kind='bar')
ax1.get_legend().remove()
ax1.set_title('Number of phages/bacteria interacting vs actual DB')
ax2 = df.iloc[[1,4,5,6,7]].plot(kind='bar')
ax2.get_legend().remove()
ax2.set_title('Number of different taxonomies with interactions')
plt.tight_layout()
The method plot from pandas would need the axes given as an argument, e.g., df.plot(ax=ax1, kind='bar'). In your example, first the figure (consisting of ax1 and ax2) is created, then another figure is created by the plot function (at the same time overwriting the original ax1 object) etc.

Matplotlibs' affine transform rotation returns a blank cell in a grid figure unless it is the last cell [duplicate]

I have searched on google but didn't get an answer. I created a subplot consisting of 2 axes and called plt.gca() but every time it only referred to the last axis in the axes of my subplots. I then started to wonder if it is possible to get a particular axis by passing in some kwargs but didn't find such parameter. I would really like to know how plt.gca() works and why you can't specify which axis to get.
gca means "get current axes".
"Current" here means that it provides a handle to the last active axes. If there is no axes yet, an axes will be created. If you create two subplots, the subplot that is created last is the current one.
There is no such thing as gca(something), because that would translate into "get current axes which is not the current one" - sound unlogical already, doesn't it?
The easiest way to make sure you have a handle to any axes in the plot is to create that handle yourself. E.g.
ax = plt.subplot(121)
ax2 = plt.subplot(122)
You may then use ax or ax2 at any point after that to manipulate the axes of choice.
Also consider using the subplots (note the s) command,
fig, (ax, ax2) = plt.subplots(ncols=2)
If you don't have a handle or forgot to create one, you may get one e.g. via
all_axes = plt.gcf().get_axes()
ax = all_axes[0]
to get the first axes. Since there is no natural order of axes in a plot, this should only be used if no other option is available.
As a supplement to Importance's very fine answer, I thought I would point out the pyplot command sca, which stands for "set current axes".
It takes an axes as an argument and sets it as the current axes, so you still need references to your axes. But the thing about sca that some may find useul is that you can have multiple axes and work on all of them while still using the pyplot interface rather than the object-oriented approach.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.subplot(121)
ax2 = plt.subplot(122)
# Check if ax2 is current axes
print(ax2 is plt.gca())
# >>> True
# Plot on ax2
plt.plot([0,1],[0,1])
plt.xlabel('X')
plt.ylabel('Y')
# Now set ax as current axes
plt.sca(ax)
print(ax2 is plt.gca())
# >>> False
print(ax is plt.gca())
# >>> True
# We can call the exact same commands as we did for ax2, but draw on ax
plt.plot([0,1],[0,1])
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
So you'll notice that we were able to reuse the same code to plot and add labels to both axes.

How can I print two boxplots on the same axis in python?

I'm using matplotlib to graph two boxplots. I am able to get them printed as subplots on the same figure, but I am having trouble getting them side by side on the same set of axes.
Here's the code which finally worked:
fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].boxplot(mads_dp52)
axes[1].boxplot(mads_dp53)
plt.show()

Displaying Main and Subplot Titles in matplotlib

As shown in the screenshot we are seeing only one title - for one of the two subplots. I am missing some detail on how to display the following three titles:
Overall plot
subplot 1
subplot 2
Here is relevant code for subplots and titles:
fig = plt.figure()
fig.suptitle('Power Iteration Clustering Inputs And Outputs') #NO show
ax = fig.add_subplot(211)
self.plotInputCircles(ax)
ax.set_title('Input Circles Data',fontsize='medium') #Shows up!
ax = fig.add_subplot(212)
self.plotOutputs(ax)
ax.set_title('Output Pseudo Eigenvector',fontsize='medium') #NO show
plt.subplots_adjust(hspace=0.1, wspace=0.2)
plt.show()
UPDATE the subroutines are corrupting the title displays (as suspected by #cel) . Per suggesion of #cel I am posting an answer stating as much.
The problem had nothing to do with titles. Per hint by #cel I looked more closely at the two subroutines that generate the subplots. One of them had a sneaky list comprehension bug.
For readers here is updated info using a dummy sin/cos that works fine instead of the subroutines.
fig = plt.figure()
fig.suptitle('Power Iteration Clustering Inputs And Outputs')
ax = fig.add_subplot(211)
x = np.linspace(-2.5,2.5,100)
ax.plot(x, np.sin(x))
# self.plotInputCircles(ax)
ax.set_title('Labeled Input Circles Data',fontsize='medium')
ax = fig.add_subplot(212)
# self.plotOutputs(ax)
x = np.linspace(-2.5,2.5,100)
ax.plot(x, np.cos(x))
ax.set_title('Output Pseudo Eigenvector',fontsize='medium')
plt.subplots_adjust(hspace=0.5, wspace=1.0)
plt.show()

Matplotlib: putting together figure, xaxis, minor_locator, major_locator

I am trying to plot a very basic plot putting several parameters together. This is how far I have come. Unfortunately the documentation and its examples does not cover my issue:
fig=plt.figure(figsize=(50,18), dpi=60)
dax_timeseries_xts.plot(color="blue", linewidth=1.0, linestyle="-", label='DAX')
# dax_timeseries_xts is a XTS with dates as index
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
Where do I create the "ax" in order to make this work?
Or maybe I am not efficiently putting the arguments listed above together to create my chart?
fig, ax_f = plt.subplots(nrows=1, ncols=1)
will give you the axes

Categories