Python中的分组X轴可变性图

问题描述 投票:2回答:1

我有一个数据集如下。我想绘制一个像JMP中的可变性图,其中Grouped X-axis有多个类别和行的图例。数据集的示例和JMP的绘图如下。是否有Pythonic解决方案来绘制此类数据?我正在寻找使用任何python绘图库的解决方案 - 散景,matplotlib,seaborn等,

Sample Data

JMP Var plot Example

python matplotlib seaborn bokeh
1个回答
0
投票

您可以尝试此代码,您需要修改绘图的xlimylim参数以适合您的实际数据:

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)

输出图表:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.