How to autoscale y axis in matplotlib? [duplicate] - matplotlib

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

Related

Adjust position of colorbar in Matplotlib subplots [duplicate]

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()

How to display all the lables present on x and y axis in matplotlib [duplicate]

I'm playing around with the abalone dataset from UCI's machine learning repository. I want to display a correlation heatmap using matplotlib and imshow.
The first time I tried it, it worked fine. All the numeric variables plotted and labeled, seen here:
fig = plt.figure(figsize=(15,8))
ax1 = fig.add_subplot(111)
plt.imshow(df.corr(), cmap='hot', interpolation='nearest')
plt.colorbar()
labels = df.columns.tolist()
ax1.set_xticklabels(labels,rotation=90, fontsize=10)
ax1.set_yticklabels(labels,fontsize=10)
plt.show()
successful heatmap
Later, I used get_dummies() on my categorical variable, like so:
df = pd.get_dummies(df, columns = ['sex'])
resulting correlation matrix
So, if I reuse the code from before to generate a nice heatmap, it should be fine, right? Wrong!
What dumpster fire is this?
So my question is, where did my labels go, and how do I get them back?!
Thanks!
To get your labels back, you can force matplotlib to use enough xticks so that all your labels can be shown. This can be done by adding
ax1.set_xticks(np.arange(len(labels)))
ax1.set_yticks(np.arange(len(labels)))
before your statements ax1.set_xticklabels(labels,rotation=90, fontsize=10) and ax1.set_yticklabels(labels,fontsize=10).
This results in the following plot:

why does plt.show() change the plt.save()?

I have multiple dimensional data set (6D), I want to plot the dimension 2/2 and save them.
But I have a problem with the save:
if I use plt.show() I get a good plot in the save_file
if I don't use plt.show() I get an awfull flot with multiple superposition
I try to figure out why
I have tried searching for the effect of plt.show on the plt.savefig but didn't found any useful information
for x in range(6):
for y in range(6):
if x != y:
plt.scatter(data.T[x],data.T[y], s=50, linewidth=0, c=cluster_member_colors, alpha=0.25)
plt.xlabel(reading_axis[x])
plt.ylabel(reading_axis[y])
plt.title(str(chip_id)+'\n ' + str(chamber_ID) + '\n '+reading_axis[x]+"vs"+reading_axis[y])
plt.savefig(save_plot_path+'/'+reading_axis[x]+"vs"+ reading_axis[y])
plt.show()
#if i remove plt.show(), the plt.savefig will save a different plot
I haven't figure yet how to post screenshot or png on stack overflow yet
but to explain what I see:
I try with and without plt.show():
with I get 4 clusters easy to differentiate
without I get 14 clusters where 10 of them are different from the 4 previous one

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:

removing ticklabels python

I am plotting a multipanel figure in python using a pandas dataframe. I have used the shorter version:
df1_5.plot(subplots=True, sharex=True);
which removes xtick labels on all but the bottom figure in a 5 row by 1 column figure format.
However in order to customize the plots, I was more explicit about how I plotted and used the following code:
fig, axes = plt.subplots(nrows=5, ncols=1, figsize=(8, 5))
df11_15['V11'].plot(ax=axes[0], ylim=(0, 7)); axes[0].set_title('V1')
df11_15['V12'].plot(ax=axes[1], ylim=(0, 7)); axes[1].set_title('V12')
df11_15['V13'].plot(ax=axes[2], ylim=(-0.5, 1.0)); axes[2].set_title('V13')
df11_15['V14'].plot(ax=axes[3], ylim=(-0.5,0.5)); axes[3].set_title('V14')
df11_15['V15'].plot(ax=axes[4], ylim=(-0.5, 0.5)); axes[4].set_title('V15')
I would like to remove the xticklabels from the upper four plots. Can you tell me how to do this?
I tried:
axes[3].set_axisticklabels()
but was told there was no attribute error named this.
Try this
for label in ax[3].get_xticklabels():
label.set_visible(False)
For completeness I will also provide example on how this works in a loop
# generate 2x4 matrix of subplots
fig, axs = plt.subplots(nrows=4, ncols=2)
for i,ax in enumerate(fig.axes):
# fill histograms with random numbers
ax.hist(np.random.normal(size = 100), bins=20)
# set the same xlim so that making labels invisible makes sense
ax.set_xlim([-4,4])
# make labels invisible only if "ax" is not in the last row
if not ax.is_last_row():
for label in ax.get_xticklabels():
label.set_visible(False)