更改 pandas 绘图后端以获取交互式绘图而不是 matplotlib 静态绘图静态、而不是、后端、pandas

2023-09-06 07:58:58 作者:站在街角、等你牵住我的手

当我使用 pandas df.plot() 时,它使用 matplotlib 作为默认的绘图后端.但这会创建静态图.我想要交互式绘图,所以我必须更改熊猫绘图背景.当我使用 .plot() 时,如何更改 pandas 的绘图后端以让不同的库创建我的绘图?

When I use pandas df.plot() it has matplotlib as a default plotting backend. But this creates static plots. I would like interactive plots, so I have to change the pandas plotting background. How do I do change the plotting backend of pandas to have a different library creating my plots when i use .plot()?

推荐答案

你需要 pandas >= 0.25 来改变 pandas 的绘图后端.

可用的绘图后端有:

matplotlibhvplot >= 0.5.1holoviewspandas_bokehplotly >= 4.8altair

所以,默认设置是:

pd.options.plotting.backend = 'matplotlib'

您可以更改 pandas 使用的绘图库,如下所示.在这种情况下,它将 hvplot/holoviews 设置为绘图后端:

You can change the plotting library that pandas uses as follows. In this case it sets hvplot / holoviews as the plotting backend:

pd.options.plotting.backend = 'hvplot'

或者也可以使用(基本一样):

pd.set_option('plotting.backend', 'hvplot')

现在您将 hvplot/holoviews 作为 pandas 的绘图后端,它将为您提供交互式 holoviews 图而不是静态 matplotlib 图.

Now you have hvplot / holoviews as your plotting backend for pandas and it will give you interactive holoviews plots instead of static matplotlib plots.

当然,您需要安装库 hvplot/holoviews + 依赖项才能正常工作.

Of course you need to have library hvplot / holoviews + dependencies installed for this to work.

这是一个生成交互式绘图的代码示例.它使用标准的 .plot() pandas 语法:

import numpy as np
import pandas as pd

import hvplot
import hvplot.pandas

pd.options.plotting.backend = 'hvplot'

data = np.random.normal(size=[50, 2])

df = pd.DataFrame(data, columns=['x', 'y'])

df.plot(kind='scatter', x='x', y='y')