【问题标题】:How to use matplotlib kwargs for custom formatting across functions?如何使用 matplotlib kwargs 跨函数自定义格式?
【发布时间】:2018-11-27 22:20:05
【问题描述】:

我正在编辑一个函数来创建日期图,它具有硬编码的格式参数。为了简洁和灵活,我正在尝试添加 format_ax 类型函数。我已经阅读了 matplotlib 中关于 custom styling 的文档,但我对如何或是否可以将所有所需的 axis.set_xxx() 参数封装到一个函数中感到困惑,您可以轻松地操纵和调用多个自定义绘图函数。首先,我想知道:我可以/如何为 ax.set 传递 kwargs 吗?

我编写的函数已经有用于格式化所需颜色的 kwargs。我尝试将相关的代码行提取到它自己的函数中。例如:

def format_ax_nicely(ax, **kwargs):
       ax.set_ylim(bottom=ymin, top=ymax)

但是当我在my_timeseries_function 中调用format_ax_nicely 时如下:format_ax_nicely(ax, ymin=ymin, ymax=ymax) 我收到错误NameError: name 'ymin' is not defined

使用ax.set() 是我考虑的另一种方法,但您不能设置大小,只能定义限制和值等。

我也试过defined heredef add_titlebox的函数定义方法,但还是不能使用kwargs。我收到了这个错误:

     File "C:\Users\ceres\code\improc\analysis\plot.py", line 390, in my_timeseries
       title(ax, title, size=20)

  TypeError: 'str' object is not callable

**edit:感谢@TheImportanceOfBeingErnest 指出这些错误发生的原因!

这是我的函数的大致结构:

def my_timeseries_function(lots of parameters, **kwargs, **plotargs):
     # set up filesaving destination
     # cleanup dataframe
     # set labels
     fig, ax = plt.subplots(figsize=figsize)
     hues = create_custom_color_values(df, cmap, **kwargs)
     ax.grid(color="k", linestyle="-", linewidth=0.05)
     for g in labels:
          # plot x,y with custom colors
     # roughly 15 lines of formatting functions like set_ylabel, ax.legend, 
     # xaxis.set_major_locator, tick_params, conditional set_ylim which 
     # would ideally be replaced by:
     format_ax_nicely(ax, **plotargs)

本题的目的是如何实现my_timeseries可以调用的“格式化”函数。但是,由于我是新手,如果 matplotlib 的用户不建议这样做,那么我次要问 样式表是否“更好”? 似乎很难调整,因为样式表是全球环境的一部分,但它也可能是我目标的一个可能答案:更轻松地设计我的情节。

附加背景 一些 Seaborn 包通过将所有格式保留在函数中来实现灵活性。我无法使用他们的包,因为我需要以他们目前无法实现的方式为点着色,而且我也无法在我正在使用的包中创建 seaborn 依赖项。

与我的班级相关的软件包:

import numpy as np
import pandas as pd
import geopandas as gp

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.dates as mdates
import matplotlib.cm as cm
try:
    import geoplot
except BaseException:
    pass

【问题讨论】:

    标签: python matplotlib formatting data-science


    【解决方案1】:

    我无法理解您在此处究竟需要什么。我确实认为使用函数来设置坐标轴样式的方法还不错。

    也许提醒一下:如果未定义变量,则无法使用。因此你得到的错误。 您拥有的选项是

    • 定义参数

      def format_ax_nicely(ax, ymin=0, ymax=1):
          ax.set_ylim(bottom=ymin, top=ymax)
      
    • 从关键字中获取参数

      def format_ax_nicely(ax, **kwargs):
          ax.set_ylim(bottom=kwargs.get("ymin", 0), top=kwargs.get("ymax", 1))
      
    • 关于标题的字体大小,应该是

      ax.title.set_size(20)
      

    一些style 选项可以通过rcParams 全局设置。它们包括字体、大小、颜色、轴刻度外观等。但是绘图的限制不是其中的一部分。不过,您可以在上下文中使用它们进行临时样式设置

    with plt.style.context(('my_style_sheet')):
        my_timeseries_function(lots of parameters, kwargs, plotargs)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多