我在创建一个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()
1条答案
按热度按时间irtuqstp1#
您可以创建一个虚拟的不可见散点图来创建图例:
您也可以创建completely custom legend。