【python】使用pandas dataframe.plot直接画箱图

使用dataframe直接画箱图

比如,有如下一组数据,直接使用dataframe.plot画图 【】:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(yourfile, sep=	, header=0, index_col=0)
df.head()
df.plot(kind=box)
plt.show()

① 调整绘制箱图参数

df.plot(kind=box,  # 选择画图类型
        title=box title,   # 图名称
        showmeans=True,  # 显示均值
        meanline=True,  # 均值线,True:使用虚线,False使用红色小三角
        showfliers=True,  # 是否显示异常值 
        rot=60, # 坐标值倾斜程度
        figsize=(15,5),  # 画图的大小
        )

使用kind参数选择画图类型: 显示均值时,设置显示线型:meanline=True 设置meanline=False:均值显示为小三角

② 设置坐标轴

y轴设置:(x轴同理)

plt.ylabel(y label)  # 设置y轴名称
plt.ylim([-2, 10])   # 设置y轴范围
plt.yticks([-2,3,5])  # 只显示指定坐标值

③ 图中添加文本或直线

plt.text(3, 5, text,  # 在坐标(3,5)处添加文本"text"
         fontsize=15,  # 设置字体大小
         color=red,  # 设置为红色
         alpha=0.5,  # 显示透明度
         )
# 也可以将文本写在图之外:(设置相应坐标即可)
plt.text(5, 2, new text,  # 在坐标(3,5)处添加文本"text"
         fontsize=15,  # 设置字体大小
         color=red,  # 设置为红色
         alpha=0.5,  # 显示透明度
         )
plt.plot((2.5,2.5), (0,5),   # 直线横坐标x是从2.5->2.5, 纵坐标y是从0-5
         color=orange,   # 设置为橙色
         alpha=0.5,   # 设置透明度
         linewidth=1,  # 设置线条粗细
        )

④ 更多参数

⑤ 散点图+箱图

展示两个数据对应的箱图组合,示例:

import matplotlib.pyplot as plt
import random


def random_lst(a, b, n):
    lst = []
    for i in range(n):
        lst.append(random.uniform(a, b))
    return lst


def data_plt(df1, df2, idx_lst):
	fig, axs = plt.subplots(nrows=4, ncols=5, figsize=(12, 10), sharex=True) # , sharey=True)
	
	for i in range(len(idx_lst)):
	    cx = i // 5  # 每行5个图
	    rx = i % 5
	    # print(cx, rx)
	    idx_name = idx_lst[i]
	    axs[cx, rx].scatter(random_lst(0.75, 1.25, len(df1[idx_name])) + random_lst(1.75, 2.25, len(df2[idx_name])),
	                        list(df1[idx_name]) + list(df2[idx_name]), s=5, c=C7, alpha=0.4)
	    axs[cx, rx].boxplot([df1[idx_name], df2[idx_name]], 
	                        labels=[A, B], showmeans=True, meanline=False, showfliers=True, widths=0.5)
	    axs[cx, rx].set_title(idx_name, fontsize=10)
	    axs[cx, rx].grid(axis="y")
	
	    plt.xlim(0, 3)
	    plt.xticks([1, 2], [A, B])
	plt.show()

idx_lst = ...  # list, 两个dataframe要选择的列
dataf1 = ...  # dataframe, data1
dataf2 = ...  # dataframe, data2
data_plt(dataf1, dataf2, idx_lst)

附:python画图示例官网: https://matplotlib.org/stable/gallery/index.html


数据的处理

    取log
df2 = np.log2(df+0.0001)  # 将数值取log
    zscore:
from scipy import stats
df.shape[0]  # 行数
df.shape[1]  # 列数
zs_arr = stats.zscore(df, axis=1, ddof=0)  # 注意输出的是数组型(array)
经验分享 程序员 微信小程序 职场和发展