【发布时间】: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 here和def 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