matplot plot graph side by side - matplotlib

I need help to plot the graph side by side instead of scrolling down. I can't figure out how to plot side by side.
I would like to show the next boxplot+histogram pic side by side and so on. just 2 boxplot+histogram per rows.
cols=bank_data.select_dtypes(['int64','float64']).columns
for i, variable in enumerate(cols):
if variable != "CLIENTNUM":
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)});
# Add a graph in each part
sns.boxplot(bank_data[variable], ax=ax_box);
sns.histplot(bank_data[variable], bins=12, kde=True, stat='density',ax=ax_hist);
ax_box.axvline(np.mean(bank_data[variable]),color='g',linestyle='-')
ax_hist.axvline(np.mean(bank_data[variable]),color='g',linestyle='-')
ax_hist.axvline(np.median(bank_data[variable]),color='y',linestyle='--')
plt.tight_layout()
boxplot+histogram pic

Related

matplotlib tick label anchor -- right align tick labels (on right side axis) and "clip" the left (west) side of the tick labels to the axis

I would like to use the "west" anchor for my tick labels for a twinx (right-side) axis. Looking at the plot below, for example, I would like the left side of the tick labels to be aligned with the right axis.
I attempted a few things below, to no avail.
import matplotlib.pyplot as plt
X = [1,2,3]
fig, ax = plt.subplots()
ax.plot(X)
ax.set_ylim([1,3])
ax.set_yticks(X)
axR = ax.twinx()
axR.set_ylim(ax.get_ylim())
axR.set_yticks(ax.get_yticks())
axR.set_yticklabels(['-1.00', '2.00', '3.00'], ha='right')
# axR.set_yticklabels(['-1.00', '2.00', '3.00'], ha='right', bbox_to_anchor='W')
# axR.set_yticklabels(['-1.00', '2.00', '3.00'], ha='right', bbox=dict(bbox_to_anchor='W'))
# bbox can have args from: https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.FancyBboxPatch.html#matplotlib.patches.FancyBboxPatch
fig.show()
So I had the same problem and stumbled on this question. I tried quite a bit and I basically decided I would need to find the right side of the labels when they are left aligned on the right side and then right align them from this point.
I tried a few things but don't have a lot of experience, so it's not perfect, but it seems to work by finding the coordinates as a bbox. I converted that back and forth to get it as an array (probably a shorter way that I don't know). I then took the gap of the largest one and added that to the spacing.
A few notes: I'm doing this on a subplot, hence ax2. I've also already moved the axis tick labels to the right side with ax2.yaxis.tick_right()
r = plt.gcf().canvas.get_renderer()
coord = ax2.yaxis.get_tightbbox(r)
ytickcoord = [yticks.get_window_extent() for yticks in ax2.get_yticklabels()]
inv = ax2.transData.inverted()
ytickdata = [inv.transform(a) for a in ytickcoord]
ytickdatadisplay = [ax2.transData.transform(a) for a in ytickdata]
gap = [a[1][0]-a[0][0] for a in ytickdatadisplay]
for tick in ax2.yaxis.get_majorticklabels():
tick.set_horizontalalignment("right")
ax2.yaxis.set_tick_params(pad=max(gap)+1)}
Update: I have recently been sent the solution to a similar problem with left alignment on the left side. From this solution, I believe this can be simplified to:
import matplotlib as mpl
import matplotlib.pyplot as plt
fig = plt.figure(figsize =(5,3))
ax = fig.add_axes([0,0,1,1])
plt.plot([0,100,200])
ax.yaxis.tick_right()
# Draw plot to have current tick label positions
plt.draw()
# Read max width of tick labels
ytickcoord = max([yticks.get_window_extent(renderer = plt.gcf().canvas.get_renderer()).width for yticks in ax.get_yticklabels()])
# Change ticks to right aligned
ax.axes.set_yticklabels(ax.yaxis.get_majorticklabels(),ha = "right")
# Add max width of tick labels
ax.yaxis.set_tick_params(pad=ytickcoord+1)
plt.show()
plt.close("all")

How to get legend next to plot in Seaborn?

I am plotting a relplot with Seaborn, but getting the legend (and an empty axis plot) printed under the main plot.
Here is how it looks like (in 2 photos, as my screen isn't that big):
Here is the code I used:
fig, axes = plt.subplots(1, 1, figsize=(12, 5))
clean_df['tax_class_at_sale'] = clean_df['tax_class_at_sale'].apply(str)
sns.relplot(x="sale_price_millions", y='gross_sqft_thousands', hue="neighborhood", data=clean_df, ax=axes)
fig.suptitle('Sale Price by Neighborhood', position=(.5,1.05), fontsize=20)
fig.tight_layout()
fig.show()
Does someone has an idea how to fix that, so that the legend (maybe much smaller, but it's not a problem) is printed next to the plot, and the empty axis disappears?
Here is my dataset form (in 2 screenshot, to capture all columns. "sale_price_millions" is the target column)
Since you failed to provide a Minimal, Complete, and Verifiable example, no one can give you a final working answer because we can't reproduce your figure. Nevertheless, you can try specifying the location for placing the legend as following and see if it works as you want
sns.relplot(x="sale_price_millions", y='gross_sqft_thousands', hue="neighborhood", data=clean_df, ax=axes)
plt.legend(loc=(1.05, 0.5))

Scatter plot without x-axis

I am trying to visualize some data and have built a scatter plot with this code -
sns.regplot(y="Calls", x="clientid", data=Drop)
This is the output -
I don't want it to consider the x-axis. I just want to see how the data lie w.r.t y-axis. Is there a way to do that?
As #iayork suggested, you can see the distribution of your points with a striplot or a swarmplot (you could also combine them with a violinplot). If you need to move the points closer to the y-axis, you can simply adjust the size of the figure so that the width is small compared to the height (here i'm doing 2 subplots on a 4x5 in figure, which means that each plot is roughly 2x5 in).
fig, (ax1,ax2) = plt.subplots(1,2, figsize=(4,5))
sns.stripplot(d, orient='vert', ax=ax1)
sns.swarmplot(d, orient='vert', ax=ax2)
plt.tight_layout()
However, I'm going to suggest that maybe you want to use distplot instead. This function is specifically created to show the distribution of you data. Here i'm plotting the KDE of the data, as well as the "rugplot", which shows the position of the points along the y-axis:
fig = plt.figure()
sns.distplot(d, kde=True, vertical=True, rug=True, hist=False, kde_kws=dict(shade=True), rug_kws=dict(lw=2, color='orange'))

Matplotlib: imshow with second y axis

I'm trying to plot a two-dimensional array in matplotlib using imshow(), and overlay it with a scatterplot on a second y axis.
oneDim = np.array([0.5,1,2.5,3.7])
twoDim = np.random.rand(8,4)
plt.figure()
ax1 = plt.gca()
ax1.imshow(twoDim, cmap='Purples', interpolation='nearest')
ax1.set_xticks(np.arange(0,twoDim.shape[1],1))
ax1.set_yticks(np.arange(0,twoDim.shape[0],1))
ax1.set_yticklabels(np.arange(0,twoDim.shape[0],1))
ax1.grid()
#This is the line that causes problems
ax2 = ax1.twinx()
#That's not really part of the problem (it seems)
oneDimX = oneDim.shape[0]
oneDimY = 4
ax2.plot(np.arange(0,oneDimX,1),oneDim)
ax2.set_yticks(np.arange(0,oneDimY+1,1))
ax2.set_yticklabels(np.arange(0,oneDimY+1,1))
If I only run everything up to the last line, I get my array fully visualised:
However, if I add a second y axis (ax2=ax1.twinx()) as preparation for the scatterplot, it changes to this incomplete rendering:
What's the problem? I've left a few lines in the code above describing the addition of the scatterplot, although it doesn't seem to be part of the issue.
Following the GitHub discussion which Thomas Kuehn has pointed at, the issue has been fixed few days ago. In the absence of a readily available built, here's a fix using the aspect='auto' property. In order to get nice regular boxes, I adjusted the figure x/y using the array dimensions. The axis autoscale feature has been used to remove some additional white border.
oneDim = np.array([0.5,1,2.5,3.7])
twoDim = np.random.rand(8,4)
plt.figure(figsize=(twoDim.shape[1]/2,twoDim.shape[0]/2))
ax1 = plt.gca()
ax1.imshow(twoDim, cmap='Purples', interpolation='nearest', aspect='auto')
ax1.set_xticks(np.arange(0,twoDim.shape[1],1))
ax1.set_yticks(np.arange(0,twoDim.shape[0],1))
ax1.set_yticklabels(np.arange(0,twoDim.shape[0],1))
ax1.grid()
ax2 = ax1.twinx()
#Required to remove some white border
ax1.autoscale(False)
ax2.autoscale(False)
Result:

Can I move about the axes in a matplotilb subplot?

Once I have created a system of subplots in a figure with
fig, ((ax1, ax2)) = plt.subplots(1, 2)
can I play around with the position of ax2, for example, by shifting it a little bit to the right or the left?
In other words, can I customize the position of an axes object in a figure after it has been created as a subplot element?
If so, how could I code this?
Thanks for thinking along
You can use commands get_position and set_position like in this example:
import matplotlib.pyplot as plt
fig, ((ax1, ax2)) = plt.subplots(1, 2)
box = ax1.get_position()
box.x0 = box.x0 + 0.05
box.x1 = box.x1 + 0.05
ax1.set_position(box)
plt.show()
which results in this:
You'll notice I've used attributes x0 and x1 (first and last X coordinate of the box) to shift the plot in 0.05 in that axis. The logic applies to y also.
In fact should the shift be to big and the boxes will overlap (like in this image with a shift of 0.2).