python - Python 中的分组 X 轴变异图

标签 python matplotlib seaborn bokeh

我有一个数据集如下。我想绘制一个像 JMP 一样的可变性图,其中分组 X 轴具有多个类别和逐行图例。 JMP 的数据集和绘图示例如下。是否有绘制此类数据的 Pythonic 解决方案?我正在寻找使用任何 python 绘图库的解决方案 - bokeh、matplotlib、seaborn 等,
Sample Data
JMP Var plot Example

最佳答案

你可以试试这个代码,你需要修改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)
# you may need these lines, if not working interactive
# plt.tight_layout()
# plt.show()
输出图表:
enter image description here

关于python - Python 中的分组 X 轴变异图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965009/

相关文章:

python - 限制一对多关系中 Many 的数量

python - 流行的火焰图标在 CKAN 中不显示

python - 曲线拟合 zipf 分布 matplotlib python

python - 在给定图上绘制一条水平线

python - 来自类别列中的类标记的多个数据帧的 pairplot 列

python - 将注释和图例保留在同一个 seaborn 图中

python - 数组列表索引超出范围

python - 在 Python 中将 RGB 像素转换为灰度。没有matplot或PIL

python - 带线的 Matplotlib 极坐标图

python - matplotlib plot_surface 命令的颜色条