在Matplotlib中为箱形图平均值和中位数线创建关键点 [英] Creating a key for box plot mean and median lines in Matplotlib
问题描述
我有以下代码可以创建APOE4基因拷贝和内存得分的箱形图(因此有变量名)
clean_merged.boxplot('composite scores',by ='APOE4',widths = 0.8,showmeans = True,meanline = True)plt.title('APOE4副本的平均复合内存得分')plt.xlabel('APOE4副本数')plt.ylabel('综合内存得分')plt.rcParams ['figure.figsize'] =(10,10)
生成以下输出:
我想为平均值(绿色虚线)和中线(实心填充)添加一个图例,并根据先前提出的问题努力做到这一点,因为我如何创建图形与通常建议的方法完全不同.>
我是python的新手,所以我们非常感谢您的帮助:)谢谢!
您可以在绘图中添加空"线,为它们分配适当的样式,颜色和标签.这些将由 plt.legend()
拾取.由于我没有您的数据,因此我以seaborn的Titanic数据集为例:
将熊猫作为pd导入导入matplotlib.pyplot作为plt将seaborn导入为snssns.set()泰坦尼克号= sns.load_dataset('titanic')titanic.boxplot('age',by ='sex',widths = 0.8,showmeans = True,meanline = True)plt.plot([],[],'-',linewidth = 1,color ='Crimson',label ='mean')plt.plot([[],[],'-',linewidth = 1,color ='gray',label ='median')plt.legend()
I have the following code which creates a box plot of APOE4 gene copies and memory scores (hence the variable names)
clean_merged.boxplot('composite scores', by='APOE4', widths = 0.8, showmeans = True, meanline = True)
plt.title('Mean Composite Memory Score by APOE4 Copies')
plt.xlabel('Number of APOE4 Copies')
plt.ylabel('Composite Memory Score')
plt.rcParams['figure.figsize'] = (10,10)
which generates this output:
I would like to add a legend for the mean (green dashed) and median lines (solid fill) and am struggling to do so based on previously asked questions as how i have created my graph is quite different to the methods usually advised.
I'm new to python so any help is appreciated :) thanks !!!
You can add "empty" lines to the plot, assigning them the appropriate styles, colors, and labels. These will be picked up by plt.legend()
. Since I don't have your data, I'm using seaborn's Titanic dataset as an example:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
titanic = sns.load_dataset('titanic')
titanic.boxplot('age', by='sex', widths=0.8, showmeans=True, meanline=True)
plt.plot([], [], '-', linewidth=1, color='Crimson', label='mean')
plt.plot([], [], '-', linewidth=1, color='gray', label='median')
plt.legend()
这篇关于在Matplotlib中为箱形图平均值和中位数线创建关键点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!