Python Seaborn绘图在同一脚本中绘制多个绘图时添加图例
我是新出生的。在同一脚本中绘制多个绘图时,第一个绘图是正确的,但对于其他绘图,会附加图例,使绘图倾斜 我的代码Python Seaborn绘图在同一脚本中绘制多个绘图时添加图例,python,pandas,seaborn,Python,Pandas,Seaborn,我是新出生的。在同一脚本中绘制多个绘图时,第一个绘图是正确的,但对于其他绘图,会附加图例,使绘图倾斜 我的代码 sns.set() cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) ax = sns.scatterplot(x="Clicks", y="Impressions", hue="Language2", size="CTR", palette=cma
sns.set()
cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)
ax = sns.scatterplot(x="Clicks", y="Impressions",
hue="Language2", size="CTR",
palette=cmap, sizes=(10, 200),
data=df)
ax.get_figure().savefig('Test plot.png')
sns.set()
cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)
ax0 = sns.scatterplot(x="Impressions", y="Clicks",
hue="Word2", size="Transactions",
palette=cmap, sizes=(10, 200),
data=df)
ax0.get_figure().savefig('Test plot 2.png')
sns.set()
cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)
ax1 = sns.scatterplot(x="CTR", y="CostPerTransaction",
hue="Language2", size="Transactions",
palette=cmap, sizes=(10, 200),
data=df)
ax1.get_figure().savefig('Test plot 3.png')
我不确定是否每次都应该使用sns.set()
。我已重命名每个ax,但问题仍然存在
另外,也许你可以建议我如何改进我的情节
谢谢您的建议。我不确定这是否能解决您的问题。但总的来说,每当在matplotlib/seaborn中创建多个绘图时,我强烈倾向于使用显式面向对象方法(matplotlib是底层库,seaborn只是包装它以使某些应用程序更快)。这意味着摆脱ax.get_figure().savefig部分。我发现与隐式状态方法相比,理解面向对象的matplotlib方法非常有用 此方法中的代码如下所示:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True)
fig1, ax1 = plt.subplots()
sns.scatterplot(x="Clicks", y="Impressions",
hue="Language2", size="CTR",
palette=cmap, sizes=(10, 200),
data=df,
ax=ax1)
# This may help with your axes labels spilling off the figure:
fig1.tight_layout()
fig1.savefig('Test plot.png')
# the sns.set is not needed each time
fig2, ax2 = plt.subplots()
# cmap is the same, so we don't need to define that again
sns.scatterplot(x="Impressions", y="Clicks",
hue="Word2", size="Transactions",
palette=cmap, sizes=(10, 200),
data=df,
ax=ax2)
fig2.savefig('Test plot 2.png')
fig3, ax3 = plt.subplots()
sns.scatterplot(x="CTR", y="CostPerTransaction",
hue="Language2", size="Transactions",
palette=cmap, sizes=(10, 200),
data=df,
ax=ax3)
fig3.savefig('Test plot 3.png')
可能您需要在保存图像后调用
plt.clf()
,以便清除绘图。谢谢您的详细回答,先生。