Python中的分组X轴可变性图 [英] Grouped X-axis Variability plot in Python

查看:111
本文介绍了Python中的分组X轴可变性图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的数据集.我想像在JMP中使用具有多个类别和逐行图例的分组X轴来绘制可变性图.下面是来自JMP的数据集和图表示例.是否存在Pythonic解决方案来绘制此类数据?我正在寻找使用任何python绘图库-bokeh,matplotlib,seaborn等的解决方案,

I have a dataset as below. I would like to plot a variability plot like in JMP with Grouped X-axis with multiple categories and legend by row. Example of dataset and Plot from JMP are below. Is there a Pythonic solution to plotting this type of data? I am looking for a solution using any of the python plotting libraries - bokeh,matplotlib,seaborn etc.,

样本数据

JMP变量图示例

推荐答案

您可以尝试使用此代码,您需要修改plot的xlimylim参数以适合您的真实数据:

You can try this code, you'll need to modify the xlim and ylim parameters of plot to fit your real data:

import pandas as pd
import matplotlib.pyplot as plt
from itertools import groupby
import numpy as np 
%matplotlib inline

df = pd.DataFrame({'Name':['John']*2+['David']*2+['Mike']*2+['Albert']*2+['King']*2+['Brown']*2,
                  'TEST_Name':['Class A']*6+['Class B']*6,
                  'Label':['Median','NINETYFIVEPERC']*6,
                  'Data':[.54,.62,.55,.62,.55,.67,.58,1.05,.54,.60,.54,.60]})
df = df.set_index(['TEST_Name','Name','Label'])['Data'].unstack()

def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='gray')
    line.set_clip_on(False)
    ax.add_line(line)

def label_len(my_index,level):
    labels = my_index.get_level_values(level)
    return [(k, sum(1 for i in g)) for k,g in groupby(labels)]

def label_group_bar_table(ax, df):
    ypos = -.1
    scale = 1./df.index.size
    for level in range(df.index.nlevels)[::-1]:
        pos = 0
        for label, rpos in label_len(df.index,level):
            lxpos = (pos + .5 * rpos)*scale
            ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)
            add_line(ax, pos*scale, ypos)
            pos += rpos
        add_line(ax, pos*scale , ypos)
        ypos -= .1

ax = df.plot(marker='o', linestyle='none', xlim=(-.5,5.5), ylim=(.3,1.1))
#Below 2 lines remove default labels
ax.set_xticklabels('')
ax.set_xlabel('')
label_group_bar_table(ax, df)

输出图表:

这篇关于Python中的分组X轴可变性图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆