向热图 Plotnine 提供十六进制颜色值

问题描述 投票:0回答:1

我正在处理一些数据,并希望使用指定的预制调色板制作热图。数据框如下所示(我在此分析中使用

polars
表示所有数据框操作)。

┌──────────────┬─────────────┬────────────────┬──────────────────────┬─────────┐
│ team1        ┆ team2       ┆ type           ┆ value                ┆ color   │
│ ---          ┆ ---         ┆ ---            ┆ ---                  ┆ ---     │
│ str          ┆ str         ┆ i64            ┆ f64                  ┆ str     │
╞══════════════╪═════════════╪════════════════╪══════════════════════╪═════════╡
│ team1_1      ┆ team2_1     ┆ 18             ┆ 115.850278           ┆ #443b84 │
│ team1_1      ┆ team2_2     ┆ 26             ┆ 24.241389            ┆ #470e61 │
│ team1_2      ┆ team2_2     ┆ 13             ┆ 3.278333             ┆ #440256 │
│ team1_1      ┆ team2_3     ┆ 30             ┆ 94.118333            ┆ #46327e │
│ team1_3      ┆ team2_3     ┆ 13             ┆ 35.186111            ┆ #481467 │
│ …            ┆ …           ┆ …              ┆ …                    ┆ …       │
│ team1_2      ┆ team2_1     ┆ 18             ┆ 67.937778            ┆ #482576 │
│ team1_2      ┆ team2_4     ┆ 22             ┆ 0.0                  ┆ #440154 │
│ team1_4      ┆ team2_2     ┆ 30             ┆ 1.199444             ┆ #440154 │
│ team1_1      ┆ team2_5     ┆ 15             ┆ 0.0                  ┆ #440154 │
│ team1_1      ┆ team2_3     ┆ 11             ┆ 8.345278             ┆ #450559 │
└──────────────┴─────────────┴────────────────┴──────────────────────┴─────────┘

在此数据集中,我尝试为每个

team2
条目绘制单个热图,但我想保留单个调色板,因此不同图之间的热图具有可比性(即,图中的深蓝色)
team2_1
的绘图与
team2_5
绘图中的深蓝色含义相同)。我使用
color
库生成了
mizani
列:

from mizani.palettes import cmap_pal

palette = cmap_pal("viridis")
palette_values = (df["value"] - df["value"].min()) / (
            df["value"].max() - df["value"].min()
        )
df = df.with_columns(color=pl.Series(palette(palette_values)))

然后,我循环遍历

team2
列中的所有唯一值,并使用
plotnine
生成热图。

for t2 in df["team2"].unique():
  df1 = df.filter(pl.col("team2") == t2)
  color_dict = {
    key: value
    for key, value in zip(df1["value"], df1["color"])
  }
  plt = (
    pn.ggplot(
      data=df1.to_pandas(),
      mapping=pn.aes(
        x="team1",
        y="type",
        label="value",
        fill="value",
      ),
    )
    + pn.geom_tile(show_legend=False)
    + pn.scale_fill_manual(color_dict)
    + pn.geom_text(show_legend=False, size=9, format_string="{:.2f}")
  )

我从

plotnine
收到错误:
TypeError: Continuous value supplied to discrete scale
。在这里实现我想要的最好方法是什么?

python colors python-polars plotnine
1个回答
0
投票

您需要将

fill
美学映射到
color
列,然后使用
scale_fill_identity

plt = (
    pn.ggplot(
      data=df1.to_pandas(),
      mapping=pn.aes(
        x="team1",
        y="type",
        label="value",
        fill="color",
      ),
    )
    + pn.geom_tile(show_legend=False)
    + pn.scale_fill_identity()
    + pn.geom_text(show_legend=False, size=9, format_string="{:.2f}")
  )
© www.soinside.com 2019 - 2024. All rights reserved.