我想根据山峰所在的位置给我的海上线条图的线条上色。这是我当前的图
如图所示,一些天的峰值在4.72,而另一些天在5.24和5.83。我想根据这些山峰来上色。因此,对于下面的图,它将有3种颜色,同时保持图例中的日期。
这是我的熊猫的数据帧,叫做select_bins
2.79 3.1 3.44 3.82 4.25 4.72 5.24 5.83 6.47 7.19 7.99 8.88
date
20180527 1 28 101 270 694 1253 1134 528 106 10 0 0
20180603 0 0 0 3 12 26 82 45 5 0 0 0
20180611 2 7 34 137 317 341 410 179 48 10 1 0
20180617 2 6 13 52 130 133 161 74 23 4 0 0
20180625 0 2 1 9 14 34 47 53 9 0 0 0
20180626 5 1 1 5 18 50 72 101 28 2 0 0
20180628 2 0 0 2 21 41 87 78 16 0 0 0
20180705 1 1 0 2 18 32 63 61 27 7 0 0
20180709 2 0 3 6 31 56 107 139 52 12 1 0
这是要绘制的代码。如您所见,我将select_bins
数据帧转置为
ax = sns.lineplot(data = select_bins.T, dashes=False, palette = 'rocket')
plt.show()
发布于 2021-01-07 11:23:21
您可以对数据进行分组并指定单独的调色板:
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
select_bins = pd.read_csv("test.txt", sep="\s{2,}", engine="python", index_col="date")
#identify unique peaks
col_bin = select_bins.idxmax(axis=1)
unique_val = np.unique(col_bin)
#provide information for palettes
palettes = ["Reds", "Blues", "Greys"]
fig, ax = plt.subplots()
#plot subgroups with their palettes, providing still individual colors within the palette for each line
for uv, pal in zip (unique_val, palettes):
sns.lineplot(data = select_bins[col_bin==uv].T, dashes=False, palette = pal, ax=ax)
plt.show()
示例输出:
或者,您可以对组使用不同的线条样式,但为此,您必须首先从wide to long form对数据进行整形。既然我们必须将日期转换为字符串,为什么不将x值转换为数字,以获得更逼真的曲线表示呢?
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt
select_bins = pd.read_csv("test.txt", sep="\s{2,}", engine="python", index_col="date")
#identify columns to plot
cols=select_bins.columns
#identify peaks
select_bins["col_bin"] = select_bins.idxmax(axis=1)
#reshape data for plotting
plot_df = select_bins.reset_index().melt(id_vars=["date", "col_bin"], value_vars=cols)
plot_df = plot_df.astype({"date": str, "variable": float})
fig, ax = plt.subplots(figsize=(10, 6))
sns.lineplot(data = plot_df, x="variable", y="value", hue="date", style="col_bin", palette = "rocket", ax=ax)
plt.xticks(ticks=[float(x) for x in cols], labels=cols)
plt.show()
示例输出:
发布于 2021-01-07 10:38:23
如果在数据框中创建其他变量,请为每行的峰值[1,2,3]
编码一个值,然后将其设置为hue
sns.lineplot(data = select_bins.T, dashes=False, palette = 'rocket', hue="peak_encoding")
https://stackoverflow.com/questions/65610611
复制