How to make spines in matplotlib figure visible? - python

I would like to make the spines in my matplotlib figure visible, but they are not showing up.
fig, ax1 = plt.subplots(figsize=(10,6))
ax1.set_title(title+' vs Delinquency', fontsize=20, fontweight='bold')
ax1.set_facecolor('none')
ax1.spines['bottom'].set_color('black')
ax1.spines['left'].set_color('black')
ax1.spines['right'].set_color('black')
ax1=sns.barplot(x=feature, y='proportion', data=data, color='midnightblue')
plt.xticks(rotation=45, fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel(title+' Group', fontsize=16)
plt.ylabel('Proportion', fontsize=16, color='midnightblue')
ax2=ax1.twinx()
ax2=sns.lineplot(x=feature, y='default_rate', data=data, color='firebrick')
plt.yticks(fontsize=12)
plt.ylabel('Default Rate', fontsize=16, color='firebrick')
plt.grid(None)
plt.show()

Related

The following is my matplotlib but i think there's something wrong in it

fig=plt.figure()
ax1=fig.add_axes([0,0,1,1])
ax2=fig.add_axes([0.2,0.5,0.4,0.4])
ax1.set_xlim([0,100])
ax1.set_ylim([0,10000])
ax2.set_xlim([20,22])
ax2.set_ylim([30,50])
ax1.set_ylabel('Z')
ax1.set_xlabel('X')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(2000))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(20))
ax2.set_ylabel('Y')
ax2.set_xlabel('X')
ax2.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(0.5))
This is printing out the following plot.
Fixed tick locators, adjusted subplot positioning, organized code a bit, hid spines, added dashed y grid, increased tick label font sizes.
fig, ax1 = plt.subplots(figsize=(12,8))
ax2 = fig.add_axes([0.575,0.55,0.3,0.3])
ax1.set_xlim([0,100])
ax1.set_ylim([0,10000])
ax1.set_xlabel('X', fontweight='bold')
ax1.set_ylabel('Z', rotation=0, fontweight='bold')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(20))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(1000))
ax1.grid(axis='y', dashes=(8,3), color='gray', alpha=0.3)
ax2.set_xlim([20,22])
ax2.set_ylim([30,50])
ax2.set_xlabel('X', fontweight='bold')
ax2.set_ylabel('Y', rotation=0, fontweight='bold')
ax2.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(5))
for ax in [ax1, ax2]:
[ax.spines[s].set_visible(False) for s in ['top','right']]
ax.tick_params(axis='both', labelsize=12, left=False, bottom=False)

Seaborn: How to specify plot minor ticks and gridlines in all plots when using lmplot?

I'm trying to get minor ticks and gridlines plotted in all plots when using lmplot, using the code below:
sns.set(context="notebook", style='white', font_scale=2)
g=sns.lmplot(data=data ,
x="x",
y="y",
col="item", # or use rows to display xplots in rows (one on top of the other)
fit_reg=False,
col_wrap=2,
scatter_kws={'linewidths':1,'edgecolor':'black', 's':100}
)
g.set(xscale='linear', yscale='log', xlim=(0,0.4), ylim=(0.01, 10000))
for ax in g.axes.flatten():
ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
ax.grid(b=True, which='both', color='gray', linewidth=0.1)
for axis in [ax.yaxis, ax.xaxis]:
formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y))
axis.set_major_formatter(formatter)
sns.despine()
g.tight_layout()
# Show the results
plt.show()
So far, only major ticks and gridlines are shwon in all plots.
Thanks for any advice for solving this
Your code work fine for me.
I think the problem is that when the major labels are too big, matplotlib chooses not to display the minor ticks, and hence the minor grid lines. You may either change font_scale, or increase the size of your figure (see height= in lmplot())
Consider the following code with font_scale=1
tips = sns.load_dataset('tips')
sns.set(context="notebook", style='white', font_scale=1)
g = sns.lmplot(x="total_bill", y="tip", col="day", hue="day",
data=tips, col_wrap=2, height=3)
g.set(xscale='linear', yscale='log')
for ax in g.axes.flatten():
ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
ax.grid(b=True, which='both', color='gray', linewidth=0.1)
for axis in [ax.yaxis, ax.xaxis]:
formatter = matplotlib.ticker.FuncFormatter(lambda y, _: '{:.16g}'.format(y))
axis.set_major_formatter(formatter)
sns.despine()
g.tight_layout()
# Show the results
plt.show()
compare with the result using font_scale=2

Put legend for all lines on the matplolit

I'm running this code to plot a graph with two-axis but I'm getting an issue to display the legend for each line plotted on for the lines for the "first axis".
#create some mark data
temp=weather.head(4)
temp.set_index('Month', inplace=True)
temp=temp.transpose()
temp_label=list(ppt.head(0))
#display(ppt)
ppt=weather.tail(1)
ppt.set_index('Month', inplace=True)
ppt=ppt.transpose()
#display(temp)
fig, ax1 = plt.subplots()
color='tab:red'
ax1.set_ylabel('Temperature', color=color)
ax1.plot(temp.index, temp.loc[:,:], label=['A','B','C','D'])
ax1.tick_params(axis='y', labelcolor=color)
leg = ax1.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)
ax2 = ax1.twinx()
color = 'tab:grey'
ax2.set_ylabel('Precipitation (mm)', color='grey')
ax2.plot(ppt.index, ppt.loc[:,:], color='grey')
ax2.tick_params(axis='y', labelcolor='grey')
leg = ax2.legend(loc='upper right', fancybox=True, shadow=False)
leg.get_frame().set_alpha(0.4)
fig.tight_layout()
plt.show()
Try:
temp.plot(ax=ax1)
instead of
ax1.plot(temp.index, temp.loc[:,:], label=['A','B','C','D'])

Matplotlib plot disappears after annotating?

fig1 = figure()
ax = fig1.add_subplot(111, autoscale_on = False)
ax.plot(data[:,0]*1E6, data[:,3]
,data[:,0]*1E6, data[:,4],'r')
plt.xlabel('Time (us)')
plt.ylabel('Voltage (V)')
plt.title('Time')
plt.grid()
ax.annotate('axes center', xy=(.5, .5), xycoords='axes fraction',
horizontalalignment='center', verticalalignment='center')
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.savefig('Time.png',orientation='landscape', pad_inches=0.1)
plt.clf()
The plot disappears after annotating. Only thing that is left after saving is the annotation. Can someone give a suggestion how to save it after annotating.

Matplotlib | Change the orientation to portrait

I have this scrip to plot 7 series in the same page. I would like to set the page orientation to Portrait. As you can see bellow, I have tried:
f.savefig(sta+'.pdf', orientation='portrait', format='pdf')
But nothing happens!
Do you have any suggestion?
f, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, sharex=True, sharey=False)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5)
ax1.plot(xtr[:num.size(xt),i], color='black')
ax2.plot(ytr[:num.size(yt),i], color='black')
ax3.plot(ztr[:num.size(zt),i], color='black')
ax4.plot(obs_dataV[:,i], color='g')
ax5.plot(obs_dataH[:,i], color='r')
ax6.plot(obs_dataP, color='g')
ax7.plot(obs_dataS, color='r')
ax1.set_title( sta+' Raw data', loc='left', fontsize='10')
ax4.set_title('Vertical and Horizontal traces', loc='left', fontsize='10')
ax6.set_title('Characteristic functions', loc='left', fontsize='10')
ax1.legend('X',loc='center right', fontsize='12')
ax2.legend('Y',loc='upper right', fontsize='12')
ax3.legend('Z',loc='upper right', fontsize='12')
ax4.legend('P',loc='upper right', fontsize='12')
ax5.legend('S',loc='upper right', fontsize='12')
ax6.legend('P',loc='upper right', fontsize='12')
ax7.legend('S',loc='upper right', fontsize='12')
f.savefig(sta+'.pdf', orientation='portrait', format='pdf')
plt.show()
Thanks in advance :-)
I think you're wanting to change the figure size, rather than anything having to do with page layout. The orientation kwarg to savefig really only applies to the PS and EPS backends. For a PDF, the page size is defined as equal to the figure size, so it has no effect.
As a quick example of what your current results might look like:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=7, sharex=True, sharey=False)
fig.subplots_adjust(hspace=0.5)
plt.show()
To change the size of the figure, use the figsize kwarg:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=7, figsize=(8, 11), sharex=True, sharey=False)
fig.subplots_adjust(hspace=0.5)
plt.show()

Categories