【问题标题】:Syntax for matplotlib parameters on a pandas histpandas hist 上 matplotlib 参数的语法
【发布时间】:2018-06-03 18:07:38
【问题描述】:

根据docs,创建数据框的pandas hist 方法可以采用参数ax 大概将某种绘图参数传递给ax 对象。我想知道的是我如何传递这些参数。这是一些代码:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.normal(0,100,size=(100, 2)), columns=['col1', 'col2'])
pd.DataFrame.hist(df,column='col1', ax={ylim(-1000,1000), set_title('new title')})

以上代码试图使用ax 参数修改y 轴范围和标题,但我不确定要使用的语法。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    hist()输出 创建了一个 Matplotlib Axes 对象。 来自plot() docs

    返回:轴matplotlib.AxesSubplot 或它们的 np.array

    您可以使用返回的内容进行调整。

    ax = df.col1.hist()
    ax.set_title('new_title')
    ax.set_ylim([-1000,1000])
    

    plot()(以及hist() 等变体)中的ax 参数用于在预定义的 Axes 元素上绘图。例如,您可以在一个绘图中使用ax 在同一表面上覆盖另一个绘图:

    ax = df.col1.hist()
    df.col2.hist(ax=ax)
    

    注意:我稍微更新了你的语法。调用 hist() 作为数据框本身的方法。

    更新
    或者,您可以直接传递关键字,但在这种情况下,您 (a) 需要调用 plot.hist() 而不仅仅是 hist(),并且 (b) 关键字作为 kwargs 或直接在行中传递。例如:

    kwargs ={"color":"green"}
    # either kwargs dict or named keyword arg work here
    df.col1.plot.hist(ylim=(5,10), **kwargs) 
    

    【讨论】:

    • 文档使您看起来可以直接通过调用hist 来执行此操作,但我仍然无法弄清楚这种方法。感谢您的解决方案。
    • 你也可以这样做。我认为你需要plot.hist(),然后你可以直接将关键字传递给 Matplotlib 的方法,比如df.col1.plot.hist(ylim=(5,10))。我将添加一个示例。
    • 直接的方式在this answer中也有引用。
    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 2015-08-18
    • 2017-05-11
    • 2023-03-05
    • 2014-07-16
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多