I met some ridiculous thing, don't know what to do with
In my app, I need to process some independent chunks of data and for each chunk create a scatterplot and save to one file and also heatmap and save to another file
So, when I plot the first chunk of data - all is okay.
When I go to 2nd there is some problem, instead of the clean background, it creates a background with gray boxes for a scatterplot graph! That's much confusing for my visualization data.
Below is a simplified example
def test_visual():
for k in range(0, 3):
fig = plt.figure()
ax = fig.add_subplot(111) # The big subplot
ax.set_aspect('equal', adjustable='box')
plt.sca(ax)
pairs_all = pd.DataFrame({'x': pd.Series(np.zeros(500), dtype=int), 'y': pd.Series(np.zeros(500), dtype=int)})
sns.scatterplot(data=pairs_all, x="x", y="y", ax=ax, s=0.15)
# plt.legend([], [], frameon=False)
ax.legend(loc='upper left', markerscale=0.2, bbox_to_anchor=(1.04, 1), fontsize=2)
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
# ax.set_xticklabels(ax.get_xticklabels(), fontsize = 4)
# ax.set_yticklabels(ax.get_yticklabels(), fontsize = 4)
plt.xticks(np.arange(0, 100 + 1, 5), fontsize=2 )
plt.yticks(np.arange(0, 100 + 1, 5), fontsize=2 )
ax.set_xlabel("")
ax.set_ylabel("")
fig.tight_layout()
output_png = '{}_{}.png'.format('file1', k)
plt.savefig(output_png, dpi=2400, bbox_inches='tight')
fig.clear()
plt.close(fig)
fig = plt.figure()
ax_w = fig.add_subplot(111) # The big subplot
# ax_w.set_aspect('equal', adjustable='box')
plt.sca(ax_w)
sns.set(font_scale=0.5)
sns.heatmap(np.zeros((100, 100)), cbar_kws={'label': 'Energy'}, ax=ax_w, cmap='plasma')
ax_w.set_xlim(0, 100)
plt.xticks(fontsize=3)
plt.yticks(fontsize=3)
# ax_w.set_title(description, fontweight='bold', fontsize=4)
fig.tight_layout()
output_png = '{}_{}.png'.format('file2', k)
plt.savefig(output_png, dpi=2400, bbox_inches='tight')
fig.clear()
plt.close(fig)
That's how it looks for the first run (file file1_0.png)
That's how it looks for the second run (file file1_1.png)
Important notice, that if do not plot heatmap the problem is gone.
So, is this is a bug from the visualization library or I need to adjust my code somehow?
When you execute sns.set(font_scale=0.5)
seaborn changes certain matplotlib rc parameters that control the appearance of matplotlib plots. In particular, by default it changes the background color and displays a grid on all subsequently created plots. You can avoid it by removing this line and using a context a manager to set rc parameters only temporarily:
with sns.plotting_context(rc={"font.size": 5.0}):
sns.heatmap(np.zeros((100, 100)),
cbar_kws={'label': 'Energy'},
ax=ax_w,
Alternatively, after plotting the heatmap you can call matplotlib.rc_file_defaults()
to restore the original matplotlib rc parameters.