我在创建 matplotlib 散点图时遇到问题,其中的图例显示点的大小直径。问题出在 scatter_plot.legend_elements 函数上。
问题是我想创建一个图例,其中的点代表 [0,25,50,75,100] 之间的值 但根据图例元素函数文档,它使图例值处于规范范围内。如何使 num 的范围在 0-100 之间,而不管 Percentage 变量的范围如何?
我很感谢您的帮助
import sys
def make_scatter_plot_by_tissue(df, size_legend="auto"):
#sort df by Percentage
df=df.sort_values(by=['Percentage'], ascending=False)
genes = df.Genes.unique()
if len(genes) > 1:
sys.stderr.write("check there is only one gene\n")
else:
gene = genes[0]
plt.figure(figsize = (20,20))
scatter_plot = plt.scatter(df['Genes'], df['Groups'],
s=df['Percentage'], c=df['Average rank'], # size of points based on percentage
cmap='Reds', alpha=0.7)
# Add a colorbar to show the mapping of colors to values
cbar = plt.colorbar(scatter_plot)
cbar.set_label('Average Rank', fontsize=20)
#set the cbar legend range to be 0-5000
plt.clim(0, 5000)
#set the cbar label font size
cbar.ax.tick_params(labelsize=20)
# code based on this https://stackoverflow.com/a/58485655/1735942
# Create a custom legend with circles representing the dot sizes
# how to make the num range between 0-100 no matter the range of Percentage variable?
size_legend = plt.legend(*scatter_plot.legend_elements(prop="sizes", num="auto"),
loc='center left', title='Percentage', bbox_to_anchor=(1.30, .5), fontsize=15)
#add grid lines to scatter_plot4
# Set the title for the size legend
size_legend.set_title('Percentage')
size_legend.get_title().set_fontsize('20')
# Display the plot
#decrease the font size on y axis
plt.yticks(fontsize=15)
plt.xticks(fontsize=15, rotation=90)
#set the xlabel font size
plt.xlabel('Genes', fontsize=20)
#set the ylabel font size
plt.ylabel('Tissue type', fontsize=20)
title_string=f"Tissue expression summmary {gene}"
plt.title(title_string, fontsize=20)
plt.show()
您可以制作一个虚拟的不可见散点图来创建图例:
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
fig, ax = plt.subplots()
scatter = ax.scatter([1, 4, 2, 3], [5, 6, 7, 8], sizes=[70, 20, 30, 80])
legend_scatter = ax.scatter(
[5, 5, 5, 5], [5, 5, 5, 5], sizes=[25, 50, 75, 100], visible=False
)
legend_elements = legend_scatter.legend_elements(prop="sizes")
ax.legend(*legend_elements)
plt.show()
您还可以创建完全自定义的图例。