gpt4 book ai didi

python - 多索引 Seaborn 线图

转载 作者:行者123 更新时间:2023-12-04 07:44:52 36 4
gpt4 key购买 nike

我有一个多索引数据框,两个索引是 Sample 和 Lithology

 Sample        20EC-P     20EC-8  20EC-10-1  ...     20EC-43    20EC-45    20EC-54
Lithology Pd Di-Grd Gb ... Hbl Plag Pd Di-Grd Gb
Rb 7.401575 39.055118 6.456693 ... 0.629921 56.535433 11.653543
Ba 24.610102 43.067678 10.716841 ... 1.073115 58.520532 56.946630
Th 3.176471 19.647059 3.647059 ... 0.823529 29.647059 5.294118
我正试图将它放入一个seaborn lineplot中。
spider = sns.lineplot(data = data, hue = data.columns.get_level_values("Lithology"),
style = data.columns.get_level_values("Sample"),
dashes = False, palette = "deep")
线图出来为
1
我有两个问题。首先,我想通过岩性和样本风格来格式化色调。在 lineplot 函数之外,我可以使用 data.columns.get_level_values 成功访问样本和岩性,但在 lineplot 中,它们似乎没有做任何事情,我还没有想出另一种访问这些值的方法。此外,线图按字母顺序重新组织 x 轴。我想强制它与数据框保持相同的顺序,但我在文档中看不到任何方法可以做到这一点。

最佳答案

使用 hue=style= ,seaborn 更喜欢 long form 中的数据帧. pd.melt() 将合并所有列并使用旧列名称创建新列,并为值创建一列。索引也需要转换为常规列(使用 .reset_index() )。
大多数seaborn函数使用order=在 x 值上设置顺序,但使用 lineplot唯一的方法是使列分类应用固定顺序。

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

column_tuples = [('20EC-P', 'Pd '), ('20EC-8', 'Di-Grd'), ('20EC-10-1 ', 'Gb'),
('20EC-43', 'Hbl Plag Pd'), ('20EC-45', 'Di-Grd'), ('20EC-54', 'Gb')]
col_index = pd.MultiIndex.from_tuples(column_tuples, names=["Sample", "Lithology"])
data = pd.DataFrame(np.random.uniform(0, 50, size=(3, len(col_index))), columns=col_index, index=['Rb', 'Ba', 'Th'])

data_long = data.melt(ignore_index=False).reset_index()
data_long['index'] = pd.Categorical(data_long['index'], data.index) # make categorical, use order of the original dataframe
ax = sns.lineplot(data=data_long, x='index', y='value',
hue="Lithology", style="Sample", dashes=False, markers=True, palette="deep")
ax.set_xlabel('')

ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.02))
plt.tight_layout() # fit legend and labels into the figure
plt.show()
sns.lineplot from multiindexed columns
长数据帧如下所示:
   index      Sample    Lithology      value
0 Rb 20EC-P Pd 6.135005
1 Ba 20EC-P Pd 6.924961
2 Th 20EC-P Pd 44.270570
...

关于python - 多索引 Seaborn 线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67247105/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com