首页 > 解决方案 > Seaborn python 在绘图上更改颜色系列

问题描述

我正在尝试更改 Seaborn 在绘图上使用的默认配色方案,我只想要一些简单的东西,例如他们文档中显示的 HLS 方案。但是他们的方法似乎不起作用,我只能假设这是由于我使用了“色调”,但我不知道如何让它正常工作。这是当前代码,datain 只是一个包含正确数字列数的文本文件,其中 p 作为索引值:

import pandas as pd
import numpy as np
datain = np.loadtxt("data.txt")
df = pd.DataFrame(data = datain, columns = ["t","p","x","y","z"])
ax3 = sns.lineplot("t", "x", sns.color_palette("hls"), data = df[df['p'].isin([0,1,2,3,4])], hue = "p")
plt.show()

该代码将前几个数据集从文件中绘制出来,如果我不包含 sns.color_palette 函数,它们会出现在 seaborn 似乎默认的奇怪的紫色柔和选择中。如果我包含它,我会收到错误:

TypeError:lineplot() 为关键字参数“hue”获取了多个值

考虑到 lineplot 函数接受的格式,这似乎有点奇怪。

标签: pythonmatplotlibcolorsseaborn

解决方案


First thing: You need to stick to the correct syntax. A palette is supplied via the palette argument. Just putting it as the third argument of lineplot will let it be interpreted as the third argument of lineplot which happens to be hue.

Then you will need to make sure the palette has as many colors as you have different p values.

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

datain = np.c_[np.arange(50),
               np.tile(range(5),10),
               np.linspace(0,1)+np.tile(range(5),10)/0.02]
df = pd.DataFrame(data = datain, columns = ["t","p","x"])

ax = sns.lineplot("t", "x", data = df, hue = "p", 
                  palette=sns.color_palette("hls", len(df['p'].unique())))

plt.show()

enter image description here


推荐阅读