首页 > 解决方案 > 从具有细分的多索引数据框中绘制多个 x 轴线图以匹配比例并可视化趋势比较

问题描述

我正在尝试比较一对两个成对的线图,以可视化如果原始值聚合(通过平均值或其他方式)趋势如何变化。

所以基本上我有一个像这样的原始数据框(但更长,大约 500 行):

名字 测量_1 测量_2 团体 测量_1_g measure_2_g
名称1 2 3 The_first_group 5 7
名称2 5 7 The_first_group 5 7
名称3 3 4 The_first_group 5 7
名称4 8 3 the_second_group 9 5
名称5 10 7 the_second_group 9 5

我尝试了多种使用 matplotlib 的方法,例如:

fig=plt.figure(figsize=(90,10))

ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)

ax.margins(x=0.02)
ax.plot( 'names', 'measure_1', data=df, marker='o', markerfacecolor='xkcd:orange', markersize=7, color='xkcd:orange', linewidth=3, label='measure 1')
ax.plot( 'names', 'measure_2', data=topology_low_norm, marker='o', markerfacecolor='xkcd:red', markersize=7, color='xkcd:red', linewidth=3, label='measure 2')
ax.set_xlabel("original names", color="xkcd:red")
ax.set_ylabel("y original", color="xkcd:orange")
ax.tick_params(axis='x', colors="xkcd:red", labelrotation=90)
ax.tick_params(axis='y', colors="xkcd:orange")

ax2.margins(x=0.02)
ax2.plot( 'group', 'measure_1_g', data=df, marker='^', markerfacecolor='xkcd:aqua', markersize=8, color='xkcd:aqua', linewidth=3, label='Grouped measure 1')
ax2.plot( 'group', 'measure_2_g', data=df, marker='^', markerfacecolor='xkcd:blue', markersize=8, color='xkcd:blue', linewidth=3, label='Grouped measure 2')
ax2.xaxis.tick_top()
ax2.yaxis.tick_right()
ax2.set_xlabel('Groups', color="xkcd:blue") 
ax2.set_ylabel('y Groups', color="xkcd:aqua")       
ax2.xaxis.set_label_position('top') 
ax2.yaxis.set_label_position('right') 
ax2.tick_params(axis='x', colors="xkcd:blue", labelrotation=90)
ax2.tick_params(axis='y', colors="xkcd:aqua")

handles,labels = [],[]
for ax in fig.axes:
    for h,l in zip(*ax.get_legend_handles_labels()):
        handles.append(h)
        labels.append(l)

plt.legend(handles,labels)

plt.savefig('draft.svg')

plt.show()

它创建的情节,但显然名称和组具有不同的比例。对于前几个项目,它是可以的,但是组测量的标记和线被移动,我需要在顶部和底部 x 轴中手动搜索以搜索 name1、name2、name3 和它们各自的组。

我尝试使用多索引数据框绘制数据,但没有成功,如下所示:

https://stackoverflow.com/a/66121322/14576642

情节已正确创建,但我有一些问题:

最大的问题:我不知道如何编辑代码以使其适应线图。如果我弄乱了代码,我会收到很多关于 set_ticks 和 ticks_labels 的设置和数量的错误。

这是我的初稿的一个例子,而不是链接的:

第一个青蓝色和橙红色峰值对应于名称和组变量,应将其叠加以比较个体值与聚合值

理想情况下,图像应该更长,因为名称 x 轴应该遵循组 x 轴的间距。

任何想法?

标签: pythonpandasmatplotlibplotdata-visualization

解决方案


推荐阅读