[英]Seaborn lineplot - data based on peaks
我想根據峰值所在的位置為 seaborn 線圖的線着色。 這是我目前的 plot
如圖所示,有些日子峰值在 bin 4.72,而在其他日子,峰值在 5.24 和 5.83。 我想根據這些峰值着色。 所以對於下面的 plot,它將有 3 種顏色,同時保持圖例中的日期。
這是我熊貓的dataframe,叫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
這是 plot 的代碼。 如您所見,我將select_bins
dataframe 轉置為 plot
ax = sns.lineplot(data = select_bins.T, dashes=False, palette = 'rocket')
plt.show()
您可以對數據進行分組並分配單獨的調色板:
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()
或者,您可以對組使用不同的行 styles 但為此您必須首先將數據從寬格式調整為長格式。 既然我們無論如何都必須將日期轉換為字符串,為什么不將 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()
如果您在 dataframe 中創建另一個變量,為每行的峰值[1,2,3]
編碼一個值,然后將其設置為hue
:
sns.lineplot(data = select_bins.T, dashes=False, palette = 'rocket', hue="peak_encoding")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.