matplotlib 创建范围为0-100的散点图例大小,无论数据的范围如何

efzxgjgh  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(106)

我在创建一个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()

irtuqstp

irtuqstp1#

您可以创建一个虚拟的不可见散点图来创建图例:

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()

您也可以创建completely custom legend

相关问题