跳到内容

可视化

Polars DataFrame 中的数据可以使用常见的可视化库进行可视化。

我们使用 Iris 数据集演示绘图功能。我们读取一个 CSV 文件,然后将一列数据与另一列进行绘图,并根据第三列进行着色。

import polars as pl

path = "docs/assets/data/iris.csv"

df = pl.read_csv(path)
print(df)
shape: (150, 5)
┌──────────────┬─────────────┬──────────────┬─────────────┬───────────┐
│ sepal_length ┆ sepal_width ┆ petal_length ┆ petal_width ┆ species   │
│ ---          ┆ ---         ┆ ---          ┆ ---         ┆ ---       │
│ f64          ┆ f64         ┆ f64          ┆ f64         ┆ str       │
╞══════════════╪═════════════╪══════════════╪═════════════╪═══════════╡
│ 5.1          ┆ 3.5         ┆ 1.4          ┆ 0.2         ┆ Setosa    │
│ 4.9          ┆ 3.0         ┆ 1.4          ┆ 0.2         ┆ Setosa    │
│ 4.7          ┆ 3.2         ┆ 1.3          ┆ 0.2         ┆ Setosa    │
│ 4.6          ┆ 3.1         ┆ 1.5          ┆ 0.2         ┆ Setosa    │
│ 5.0          ┆ 3.6         ┆ 1.4          ┆ 0.2         ┆ Setosa    │
│ …            ┆ …           ┆ …            ┆ …           ┆ …         │
│ 6.7          ┆ 3.0         ┆ 5.2          ┆ 2.3         ┆ Virginica │
│ 6.3          ┆ 2.5         ┆ 5.0          ┆ 1.9         ┆ Virginica │
│ 6.5          ┆ 3.0         ┆ 5.2          ┆ 2.0         ┆ Virginica │
│ 6.2          ┆ 3.4         ┆ 5.4          ┆ 2.3         ┆ Virginica │
│ 5.9          ┆ 3.0         ┆ 5.1          ┆ 1.8         ┆ Virginica │
└──────────────┴─────────────┴──────────────┴─────────────┴───────────┘

使用 Altair 进行内置绘图

Polars 有一个 `plot` 方法,可以使用 Altair 创建绘图。

chart =  (
    df.plot.point(
        x="sepal_width",
        y="sepal_length",
        color="species",
    )
    .properties(width=500, title="Irises")
    .configure_scale(zero=False)
    .configure_axisX(tickMinStep=1)
)
chart.encoding.x.title = "Sepal Width"
chart.encoding.y.title = "Sepal Length"
chart

这是以下内容的简写:

import altair as alt

(
    alt.Chart(df).mark_point(tooltip=True).encode(
        x="sepal_length",
        y="sepal_width",
        color="species",
    )
    .properties(width=500)
    .configure_scale(zero=False)
)

这样做仅为方便起见,并表明 Altair 已知与 Polars 良好兼容。

对于配置,我们建议阅读 图表配置。例如,您可以:

  • 使用 `.properties(width=500, height=350, title="My amazing plot")` 更改宽度/高度/标题。
  • 使用 `.configure_axisX(labelAngle=30)` 更改 X 轴标签旋转。
  • 使用 `.configure_point(opacity=.5)` 更改散点图中点的透明度。

hvPlot

如果您导入 `hvplot.polars`,它将注册一个 `hvplot` 方法,您可以使用该方法通过 hvPlot 创建交互式绘图。

import hvplot.polars
df.hvplot.scatter(
    x="sepal_width",
    y="sepal_length",
    by="species",
    width=650,
    title="Irises",
    xlabel='Sepal Width',
    ylabel='Sepal Length',
)
hvplot_散点图

Matplotlib

要创建散点图,我们可以将 `DataFrame` 的列直接作为每个列的 `Series` 传递给 Matplotlib。Matplotlib 不直接支持 Polars 对象,但可以通过将其转换为 NumPy 数组(对于不含空值的数值数据而言是零拷贝的)来接受 Polars `Series`。

请注意,由于列 `'species'` 不是数值类型,我们首先需要将其转换为数值,以便可以将其作为参数传递给 `c`。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter(
    x=df["sepal_width"],
    y=df["sepal_length"],
    c=df["species"].cast(pl.Categorical).to_physical(),
)
ax.set_title('Irises')
ax.set_xlabel('Sepal Width')
ax.set_ylabel('Sepal Length')

Plotnine

Plotnine 是 ggplot2 在 Python 中的重新实现,它以类似于 R 对应库的界面,为 Python 用户带来了图形语法。它通过内部将其转换为 pandas `DataFrame` 来支持 Polars `DataFrame`。

from plotnine import ggplot, aes, geom_point, labs

(
    ggplot(df, mapping=aes(x="sepal_width", y="sepal_length", color="species"))
    + geom_point()
    + labs(title="Irises", x="Sepal Width", y="Sepal Length")
)

Seaborn 和 Plotly

SeabornPlotly 可以通过利用 DataFrame 交换协议 来接受 Polars `DataFrame`,该协议在可能的情况下提供零拷贝转换。请注意,该协议不支持所有 Polars 数据类型(例如 `List`),因此在此方面的效果可能因情况而异。

Seaborn

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
sns.scatterplot(
    df,
    x="sepal_width",
    y="sepal_length",
    hue="species",
    ax=ax,
)
ax.set_title('Irises')
ax.set_xlabel('Sepal Width')
ax.set_ylabel('Sepal Length')

Plotly

import plotly.express as px

px.scatter(
    df,
    x="sepal_width",
    y="sepal_length",
    color="species",
    width=650,
    title="Irises",
    labels={'sepal_width': 'Sepal Width', 'sepal_length': 'Sepal Length'}
)