猿问

猴子修补 Pandas 和 matplotlib 以去除 df.plot() 的刺

问题:


我试图掌握猴子修补的概念,同时制作一个函数来产生完美的时间序列图。如何在 pandas pandas.DataFrame.plot() 中包含以下 matplotlib 功能?


ax.spines['top'].set_visible(False)

ax.spines['right'].set_visible(False)

ax.spines['bottom'].set_visible(False)

ax.spines['left'].set_visible(False)

complete code at the end of the question


细节:


我认为 中的默认设置df.plot()非常简洁,尤其是当您运行带有深色主题的 Jupyter Notebook 时,例如来自dunovank 的chesterish:

我想尽可能多地将它用于我的数据分析工作流程,但我真的很想像这样删除框架(或所谓的刺):

http://img1.mukewang.com/6177c4d40001a3d403930326.jpg

可以说,这是一个完美的时间序列图。但df.plot()对此没有内置参数。最接近的似乎是grid = False,但这会在同一次运行中带走整个网格:

http://img4.mukewang.com/6177c4df0001634703900320.jpg

我试过的


我知道我可以将spine代码片段包装在一个函数中,df.plot()所以我最终得到了这个:


片段 1:


def plotPerfect(df, spline):


    ax = df.plot()


    if not spline:

        ax.spines['top'].set_visible(False)

        ax.spines['right'].set_visible(False)

        ax.spines['bottom'].set_visible(False)

        ax.spines['left'].set_visible(False)


    return(ax)


plotPerfect(df = df, spline = False)

输出 1:

http://img.mukewang.com/6177c4ed000150dc03770330.jpg

但就未来修订的灵活性和可读性而言,这是“最佳”方式吗?如果我们谈论数百个情节,甚至在执行时间方面是最快的?


我知道如何获得df.plot() 源代码,但是那里的所有内容都让我感到困惑。那么,如何做我包括这些设置df.plot?也许包装函数方法和猴子补丁一样好?


包含完整代码和示例数据的片段:


要 100% 重现示例,请将其粘贴到带有chesterish theme激活的 Jupyter Notebook 单元格中:


# imports

import pandas as pd

import numpy as np

from jupyterthemes import jtplot


# Sample data

np.random.seed(123)

rows = 50

dfx = pd.DataFrame(np.random.randint(90,110,size=(rows, 1)), columns=['Variable Y'])

dfy = pd.DataFrame(np.random.randint(25,68,size=(rows, 1)), columns=[' Variable X'])

df = pd.concat([dfx,dfy], axis = 1)

jtplot.style()


# Plot with default settings

df.plot()


# Wrap df.plot() and matplotlib spine in a function

def plotPerfect(df, spline):


    ax = df.plot()


    if not spline:

        ax.spines['top'].set_visible(False)

        ax.spines['right'].set_visible(False)

        ax.spines['bottom'].set_visible(False)

        ax.spines['left'].set_visible(False)


    return(ax)


# Plot the perfect time-series plot

plotPerfect(df = df, spline = False)


12345678_0001
浏览 243回答 3
3回答

慕少森

另一个答案的替代解决方案是使用plt.box(False)或ax.set_frame_on(False),这两者都隐藏了轴矩形补丁。def plotPerfect(df, spline):    ax = df.plot()    if not spline:        ax.set_frame_on(False)        # plt.box(False)  # another possible option    return ax请注意,set_frame_on(False)删除背景使其透明,这可能是不需要的

RISEBY

我会部分回答您的问题的自定义部分:您可以将它们放入for循环中,而不是通过单独的命令隐藏每个样条,如下所示。def plotPerfect(df, spline):    ax = df.plot()    if not spline:        for i in ['top', 'right', 'bottom', 'left']:            ax.spines[i].set_visible(False)    return(ax)# Plot the perfect time-series plotplotPerfect(df = df, spline = False) 如果你想隐藏所有四个脊椎,又不想手动指定顶部、右侧等,可以采用更自动化的方式进行,如下所示。第一个允许您选择隐藏哪些。def plotPerfect(df, spline):    ax = df.plot()    if not spline:        for i in ax.spines.values():            i.set_visible(False)    return(ax)
随时随地看视频慕课网APP

相关分类

Python
我要回答