简体   繁体   中英

Matplotlib legend does not match seaborn bubble plot sizes

I have created a bubble plot using seaborn, and used matplotlib to draw the legend to the right of my seaborn plots. I specified the sizing of the bubbles in my seaborn code using sizes=(1,900) but the scaling on my matplotlib legend does not reflect what the plots show. The legend reads from 0 to 45 but the actual data in my plots range from 0 to 900

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11,4))
sns.scatterplot(y="Min", x="Max",
                size="Count", sizes=(1,900), alpha=0.5,
                color='r', data=code1, ax=ax1, legend=False)
sns.scatterplot(y="Min", x="Max", alpha=0.5,
                color='b', size="Count", sizes=(1,900),
                data=code2, ax=ax2, legend=False)
sns.scatterplot(y="Min", x="Max", alpha=0.5,
                color='g', size="Count", sizes=(1,900),
                data=code3, ax=ax3)
ax3.legend(loc='upper right', bbox_to_anchor=(1.7,1), labelspacing=2,
           fontsize=14, frameon=False, markerscale=1)

Here is my plot

这是我的情节的截图

I was unable to figure out how seaborn structures the legend output for ingestion by matplotlib. I did learn that my data (code1, code2, and code3) had different min and max values which should have been specified under seaborn's sizes argument. For code1, sizes=(1,900); for code2, sizes=(1,300); for code3, sizes=(1,45). Because I was using matplotlib to draw the legend to the right of code3's plot, the scaling was specific to the rightmost plot rather than for all 3 plots. In the end, I ended up using matplotlib's legend_elements as follows:

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12,4))
scatter = ax1.scatter(y=code1["Min"], x=code1["Max"],
                s=code1["Count"], 
                color='r', alpha=0.5)
ax2.scatter(y=code2["Min"], x=code2["Max"], 
                     color='b', s=code2["Count"], alpha=0.5)
ax3.scatter(y=code3["Min"], x=code3["Max"], 
                     color='g', s=code3["Count"], alpha=0.5)

kw = dict(prop="sizes", num=[10,100,500,900])
legend = ax3.legend(*scatter.legend_elements(**kw), title="Count", fontsize=12,
                    loc='upper right', bbox_to_anchor=(1.5,1), labelspacing=2,
                   frameon=False)

使用 matplotlib 而不是 seaborn 更新绘图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM