线条颜色作为 pandas 数据框中列值的函数

2023-11-30

我正在尝试将 pandas 数据框的两列相互绘制,并按第三列中的值进行分组。每条线的颜色应由第三列确定,即每组一种颜色。

例如:

import pandas as pd
from matplotlib import pyplot as plt

fig, ax = plt.subplots()

df = pd.DataFrame({'x': [0.1,0.2,0.3,0.1,0.2,0.3,0.1,0.2,0.3],'y':[1,2,3,2,3,4,4,3,2], 'colors':[0.3,0.3,0.3,0.7,0.7,0.7,1.3,1.3,1.3]}) 

df.groupby('colors').plot('x','y',ax=ax)

Current output

如果我这样做,我最终会得到三条不同的线,绘制 x 对 y,每条线具有不同的颜色。我现在想通过“颜色”中的值确定颜色。如何使用渐变颜色图来做到这一点?


看起来seaborn正在根据色调的值自动应用颜色强度。

import pandas as pd 
from matplotlib import pyplot as plt

df = pd.DataFrame({'x': [0.1,0.2,0.3,0.1,0.2,0.3,0.1,0.2,0.3,0.1,0.2,0.3],'y':[1,2,3,2,3,4,4,3,2,3,4,2], 'colors':[0.3,0.3,0.3,0.7,0.7,0.7,1.3,1.3,1.3,1.5,1.5,1.5]})

import seaborn as sns

sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors')

Gives:

plot

您可以通过添加调色板参数来更改颜色,如下所示:

import seaborn as sns

sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors', palette = 'mako')
#more combinations : viridis, mako, flare, etc.

gives:

mako color palette

编辑(对于颜色图):

基于答案在条形图中使用色调时,使seaborn 显示颜色条而不是图例?

import seaborn as sns

fig = sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors', palette = 'mako')

norm = plt.Normalize(vmin = df['colors'].min(), vmax = df['colors'].max())
sm = plt.cm.ScalarMappable(cmap="mako", norm = norm)
fig.figure.colorbar(sm)
fig.get_legend().remove()
plt.show()

gives..

enter image description here

希望有帮助..

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

线条颜色作为 pandas 数据框中列值的函数 的相关文章

随机推荐