Problem plotting spectrogram colorbar in matplotlib [duplicate] - python

This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 1 year ago.
I want to make a subplot using the input data

I think this is just a question of passing the spectrogram's "mappable" to plt.colorbar() so that it knows what to make a colourbar for. The tricky thing is that it's a bit buried in an attribute of the spectrogram Axes:
fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(time, data1[0].data)
ax2.plot(time, data2.data)
spec = data2.spectrogram(axes=ax3, # <-- Assign a name.
show=True,
samp_rate=20,
per_lap=0.5,
wlen=30,
log=True,
cmap='plasma', # <-- Don't use jet :)
clip=(0.05, 0.2),
)
plt.xlabel('Time')
plt.ylabel('Frequency')
# More flexibility with the positioning:
cbar_ax = fig.add_axes([0.2, 0.0, 0.6, 0.05]) # Left, bottom, width, height.
cbar = fig.colorbar(spec.collections[0], # <-- Get the mappable.
cax=cbar_ax,
orientation='horizontal')
cbar.set_label('Colorbar label')
plt.show()
This also shows how to position the colorbar where you want. And I changed your colourmap to plasma because you shouldn't use jet.

Related

matplotlib shared axis (twinx) hide y_axis values [duplicate]

This question already has an answer here:
Matplotlib: Colour multiple twinx() axes
(1 answer)
Closed 3 years ago.
I'm using the ax2 = ax1.twinx() attribute to have several graphs(3) with different scaling in the same plot, unfortunately, the values of the y-axis "run on top of each other" as shown here (right y axis, the blue values are sometimes hidden)
Here is the code for the graphs for reference
fig, ax1 = plt.subplots()
mpl.rcParams['lines.linewidth'] = 0.4
SMOOTH_FAC = 0.85
color = 'tab:red'
ax1.set_xlabel('Iterations')
ax1.set_ylabel('Non metric loss', color=color)
ax1.plot(smooth(net_loss,SMOOTH_FAC), color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('Metric supervised loss', color=color) # we already handled the x-label with ax1
ax2.plot(smooth(metric_super_loss,SMOOTH_FAC), color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax3 = ax1.twinx()
color = 'tab:orange'
ax3.set_ylabel('Supervised loss', color=color,labelpad=20) # we already handled the x-label with ax1
ax3.plot(smooth(supervised_loss,SMOOTH_FAC),color=color, zorder=1)
ax3.tick_params(axis='y', labelcolor=color)
ax1.set_zorder(ax2.get_zorder()+ax3.get_zorder()+1)
ax1.patch.set_visible(False)
fig.tight_layout()
you can use get_yaxis().set_ticks() for each axes and set the tick to a blank list []
ax1.get_yaxis().set_ticks([])
ax2.get_yaxis().set_ticks([])
ax2.get_yaxis().set_ticks([])
or you can use the set_yticklabels() function to set tick for each axes.
ax1.set_yticklabels([])
ax2.set_yticklabels([])
ax3.set_yticklabels([])
or you can add left=False, right=False, labelleft=False, labelright=False params to your tick_params() for each axes
ax1.tick_params(axis='y', labelcolor=color,left=False, right=False,labelleft=False, labelright=False)
first one is cleaner.

Seaborn stacking bars in multiple countplots located within a subplot [duplicate]

This question already has answers here:
How to have clusters of stacked bars
(10 answers)
Closed 4 years ago.
Is there a way to stack the bars in countplot so each bar contains two colors.
My code so far:
fig, axes = plt.subplots(4, 4, figsize=(15,13), sharex=True)
axes = axes.flatten()
object_bol = df.dtypes == 'object'
for ax, catplot in zip(axes, df.dtypes[object_bol].index):
sns.countplot(y=catplot, data=df, ax=ax, hue = "Attrition")
plt.tight_layout()
plt.show()
My current visualization is below along with the stacked graph I am looking to implement.
You can pass keyword arguments to plt.bar from seaborn.countplot.
You can, therefore use the bottom argument. For example (using plt.bar):
x = np.arange(0,11,1)
y = x**2
plt.bar(x, y)
plt.bar(x, y, bottom=y)
plt.xlabel('x')
plt.ylabel('y')
Gives:

Increasing the h-size of plots in plt.subplot() inside a loop - Python [duplicate]

This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 4 years ago.
I have this code:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
plt.subplot(1,2,1)
sns.boxplot(x=i, y="Y", data=df)
plt.subplot(1,2,2)
sns.boxplot(x=i, y="Temp", data=df)
plt.tight_layout()
plt.show()
It gives me all the plots I need. Here is one-time loop:
As you can see, the x axis is overlapped and I'm trying to increase the horizontal size of each plot in order to have a better visualization.
You are limited by the width of your figure. You can make your figure wider with the figsize attribute. You can "grab" your figure by either explicitly defining it (plt.figure) or getting the current figure (plt.gcf).
However, I prefer is using plt.subplots to define both figure and axes:
for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
fig, axes = plt.subplots(ncols=2, figsize=(15, 5)) # set width of figure and define both figure and axes
sns.boxplot(x=i, y="Y", data=df, ax=axes[0])
sns.boxplot(x=i, y="Temp", data=df, ax=axes[1])
plt.tight_layout()
plt.show()
Alternatively, you could decrease the number of ticks in the x axis.

Matplotlib: Convert the legend to a bitmap [duplicate]

This question already has answers here:
Get legend as a separate picture in Matplotlib
(11 answers)
Closed 4 years ago.
I want the legend as a separate bitmap, is that possible with matplotlib?
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r')
legend = axes.legend()
How would I save legend to bitmap? Any ideas?
If you want to have a legend in a different figure, you can use axes.get_legend_handles_labels() to get the legend handles and labels and add them to a different figure.
Also you need to provide a legend in the first plot, using the label argument, or to explicitly provide a list of labels to associate with the handles.
The following code should do what I suggested in my comment to the question:
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r', label='test')
legend = axes.legend()
fig2 = plt.figure()
ax = fig2.add_subplot(111)
# add the legend from a different axes
ax.legend(*axes.get_legend_handles_labels())
# hide the spines and the x/y labels
ax.axis('off')
If you want more control for hiding stuff you can hide the axis spines only with
ax.set_frame_on(False)
or the x/y labels with
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

matplotlib fig size with colorbar

I'm trying to produce two figure. The second one is equal to the first one, with the only exception that it has superimposed an image with the corresponding colorbar. I need this in a presentation for a correct overlay. The code I'm using is the following
import matplotlib as mpl
# first figure
fig = mpl.pylab.figure(figsize=(10, 7))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x,y)
ax.set_xlabel(r'x')
ax.set_ylabel(r'y')
ax.set_xlim([0,1])
ax.set_ylim([0,1])
mpl.pylab.savefig('one.pdf',bbox_inches='tight')
# second figure
fig = mpl.pylab.figure(figsize=(10, 7))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x,y)
ax.set_xlabel(r'x')
ax.set_ylabel(r'y')
ax.set_xlim([0,1])
ax.set_ylim([0,1])
im = ax.imshow(image,aspect='auto',origin='lower',extent=(0,1,0.5,1))
cb = fig.colorbar(im, orientation='vertical')
cb.set_label(r'p$_e$ [Pa]', fontsize = 18)
mpl.pylab.savefig('two.pdf',bbox_inches='tight')
The problem is that I would like that the canvas (I think this is the correct name, i.e. the space occupied by the axis and label) to be exactly the same for the two figures, whereas the second one is shrink because of the colorbar. How can I correctly determine the size for the figures?
Check out this post
You can also check out this example
I would recommend either plotting both plots on the same figure, making a grid, or doing a separate colorbar as in this example
import matplotlib as mpl
# first plot
plt.subplot(131)
...
# second plot
plt.subplot(132)
...
#colorbar
plt.subplot(133)
...

Categories

Resources