python - 从具有细分的多索引数据框中绘制多个 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
情节已正确创建,但我有一些问题:
- 我没有找到将两个 x 轴拆分为顶部(多索引的第一级 [组])和底部(第二个 [名称])的方法。
- 我没有找到将外部 x 轴旋转 90 度的方法,如果我
rotation=90
在另一个答案中提供的代码中添加了内部 x 轴就可以了。 - 该组的度量是重复条,如果我创建一个具有 4 个级别的多索引:组、度量_1_g、度量_2_g、名称;那么我不知道如何管理绘图以仅显示叠加组内容的组的一个值(而不是 4 个值对 4 个值)
最大的问题:我不知道如何编辑代码以使其适应线图。如果我弄乱了代码,我会收到很多关于 set_ticks 和 ticks_labels 的设置和数量的错误。
这是我的初稿的一个例子,而不是链接的:
第一个青蓝色和橙红色峰值对应于名称和组变量,应将其叠加以比较个体值与聚合值
理想情况下,图像应该更长,因为名称 x 轴应该遵循组 x 轴的间距。
任何想法?
解决方案
推荐阅读
- java - 反序列化后如何处理瞬态实体
- java - 从地图中调用对象并直接投射
- reactjs - 检查变量是否属于Typescript中的动态可变自定义类型
- c# - 连续背景画笔动画
- python - 为什么我的查询集在 Django 中评估后会改变大小?
- amazon-s3 - S3 Replication - s3:PutReplicationConfiguration
- python-3.x - 文本未显示在 pygame 屏幕上
- python - 如何更新 openai.gym.spaces.Dict 状态?
- javascript - 为什么我不能从 cloudinary 调整我的图像大小
- python - ASP.net 网页中的 jQuery Ajax 请求 - 有效负载构造?