Adjust position of colorbar in Matplotlib subplots [duplicate] - matplotlib

This question already has answers here:
Python matplotlib - how to move colorbar without resizing the heatmap?
(1 answer)
Matplotlib: let color bar not affect size and proportions of the plot
(2 answers)
How do I maintain image size when using a colorbar?
(2 answers)
Adjusting subplots to make space for colorbar
(1 answer)
Closed last month.
The Plot I Want to Fix
I am trying to graph three graphs stacked on top of each other and for the most part it works fine.
However when I add a colorbar to the last spectogram plot it completely squishes the plot, making the overall figure ugly.... How do I fix this?
fig, ax = plt.subplots(3, sharex=True, figsize=(50, 10))
fig.suptitle('Test' + str("%03d" % (i,)) + '+ Noisereduce', fontsize=48)
ax[0].plot(time, raw, color='blue')
ax[0].plot(time, fltr, color='orange')
ax[0].set_title('Raw Signal')
ax[1].plot(time, fltr, color='orange')
ax[1].set_title('noisereduce (stationary filter)')
spect = ax[2].pcolormesh(t, f, 10*np.log10(Sxx), vmin=vmin, vmax=vmax, shading='gouraud')
ax[2].set(xlabel='Time [sec]', ylabel='Frequency [Hz]')
fig.colorbar(spect, ax=ax[2])
ax[2].set_title('noisereduce - spectogram (upper 67% of intensities)')
plt.show()

Related

matplotlib annotations shift to the right [duplicate]

This question already has answers here:
How to fix overlapping annotations / text
(5 answers)
scatter plot with aligned annotations at each data point
(1 answer)
Closed 9 months ago.
I'm plotting both a line and some scatter points on the line. I want to label the x-coordinate of the scatter points on the line, and the annotations are being obstructed by the line. Without manually inputting the position of the annotations, is there a way to shift all of the annotation texts to the right by a certain amount?
Below is part of the code to produce the scatter plot and annotation.
import numpy as np
import matplotlib.pyplot as plt
fs = 20
figure, ax1 = plt.subplots()
ax1.set_xlim(1.6, 2.0)
ax1.set_ylim(-2, 5)
annotations = ['$1.66$', '$1.68$', '$1.72$', '$1.74$', '$1.76$']
xpoint = [1.66, 1.68, 1.72, 1.74, 1.76]
ypoint = [3.47072347e-01, 5.05186795e+00, 1.61807901e+01, 5.60855544e+01, 6.07027325e+02]
ax1.scatter(xpoint, np.log10(ypoint), color='k')
for i, label in enumerate(annotations):
ax1.annotate(label, (xpoint[i], np.log10(ypoint[i])), ha='left', va='center', fontsize=fs)
ax1.tick_params(labelsize=fs)
figure.savefig("plot.svg", bbox_inches='tight')

Seaborn colorbar height to match heatmap [duplicate]

This question already has answers here:
How to set Matplotlib colorbar height for image with aspect ratio < 1
(2 answers)
Set Matplotlib colorbar size to match graph
(9 answers)
Setting the size of a matplotlib ColorbarBase object
(2 answers)
Closed 11 months ago.
There are a few examples showing how to use "shrink" for changing the colorbar. How can I automatically figure out what the shrink should be so the colorbar is equal to the height of the heatmap?
I don't have a matplotlib axis because I am using seaborn and plotting the heatmap from the dataframe.
r = []
r.append(np.arange(0,1,.1))
r.append(np.arange(0,1,.1))
r.append(np.arange(0,1,.1))
df_cm = pd.DataFrame(r)
sns.heatmap(df_cm, square=True, cbar_kws=dict(ticks=[df_cm.min().min(), df_cm.max().max()]))
plt.tight_layout()
plt.savefig(f'test.png', bbox_inches="tight")

How to remove ylabel from Seaborn histplot? [duplicate]

This question already has an answer here:
How to remove or hide y-axis ticklabels from a matplotlib / seaborn plot
(1 answer)
Closed 5 months ago.
This is what I have:
fig, ax = plt.subplots(figsize=(4, 3))
sns.histplot(my_data, ax=ax)
ax.set(ylabel='')
But this still seems to allocate the space for the y-axis label, it's only that the label itself is an empty string, which results in wasted space on the left-hand side of the image. I don't want the white space in place of the y-axis label, I really want to remove it.
Both answers suggested in the comments work.
One way to achieve what I want is:
fig, ax = plt.subplots(figsize=(4, 3))
sns.histplot(my_data, ax=ax)
ax.set(ylabel='')
plt.tight_layout(pad=0)
The pad parameter of tight_layout controls the size of the margin around the figure.

How to remove all padding in matplotlib subplots when using images [duplicate]

This question already has answers here:
How to combine gridspec with plt.subplots() to eliminate space between rows of subplots
(1 answer)
How to remove the space between subplots in matplotlib.pyplot?
(5 answers)
Closed 3 years ago.
When creating subplots with matplotlib i cannot get tight layout where there would not be any spaces between subplot items.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 3, figsize=(10,10),gridspec_kw = {'wspace':0, 'hspace':0})
for i, ax in enumerate(axes.ravel()):
im = ax.imshow(np.random.normal(size=200).reshape([10,20]))
ax.axis('off')
plt.tight_layout()
Subplots would consist of images. Seems like there is way to do this when you are not using images. So i assume, there is some configuration about imshow().
I would like to keep aspect ratio of images, but make subplots compact as possible.
this is what i get now, but as you can see, there is a lot of row padding
https://imgur.com/a/u4IntRV

How to autoscale y axis in matplotlib? [duplicate]

This question already has an answer here:
Add margin when plots run against the edge of the graph
(1 answer)
Closed 8 years ago.
I'm currently creating many plots and some look great while other need some adjustment. From below how can I make the hard to see plot line easier to see without having to manually plot them? I plot 50-100 of these at a time then add them to a pdf report. I'd like to add space under the line, for example have ylim min limit set to -0.1, but do it automatically.
This one is hard to see plot line:
This one is easy to see plot line:
Here is my code for plotting:
def plot(chan_data):
'''Uses matplotlib to plot a channel
'''
f, ax = plt.subplots(1, figsize=(8, 2.5))
x = dffinal['time'].keys()
ax.plot(x, dffinal[chan_data].values, linewidth=0.4, color='blue')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y - %H:%M'))
ax.xaxis.set_major_locator(mdates.AutoDateLocator(interval_multiples=True))
lgd1 = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
f.autofmt_xdate()
ax.set_ylabel(dffinal[chan_data].name)
ax.grid('on')
#I've tried these with no luck
#ax.autoscale(enable=True, axis='y', tight=False)
#ax.set_ymargin(0.5)
#ax.set_autoscaley_on(True)
fname = ".\\plots\\" + chan_data + ".png"
print "Creating: " + fname
plt.savefig(fname, dpi=100, bbox_extra_artist=(lgd1,), bbox_inches='tight')
plt.close()
return fname
You want margins doc
ex
ax.margins(y=.1)
Also see Add margin when plots run against the edge of the graph