带有 matplotlib 的 Python - 重用绘图函数 [英] Python with matplotlib - reusing drawing functions

查看:36
本文介绍了带有 matplotlib 的 Python - 重用绘图函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此

I have a follow up question to this question.

Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?

For example, if I have the following functions:

FunctionA: Draw a histogram of something
FunctionB: Draw a box with a text in it
FunctionC: Draw a plot of something C
FunctionD: Draw a plot of something D

How do I go about reusing the above functions in different scripts? If I wanted, for instance, to create a figure with a histogram with a plot of something C, I would somehow call FunctionA and FunctionC from my script. Or, if I wanted a figure with the two plots, I'd call FunctionC and FunctionD.

I'm not sure if I'm explaining myself clearly, but another way of asking this question is this: how do I pass a figure object to a function and then have the function draw something to the passed figure object and then return it back to the main script to add other things like the title or something?

解决方案

Here you want to use the Artist objects, and pass them as needed to the functions:

import numpy as np
import matplotlib.pyplot as plt

def myhist(ax, color):
    ax.hist(np.log(np.arange(1, 10, .1)), facecolor=color)

def say_something(ax, words):
    t = ax.text(.2, 20., words)
    make_a_dim_yellow_bbox(t)

def make_a_dim_yellow_bbox(txt):
    txt.set_bbox(dict(facecolor='yellow', alpha=.2))

fig = plt.figure()
ax0 = fig.add_subplot(1,2,1)
ax1 = fig.add_subplot(1,2,2)

myhist(ax0, 'blue')
myhist(ax1, 'green')

say_something(ax0, 'this is the blue plot')
say_something(ax1, 'this is the green plot')

plt.show()

这篇关于带有 matplotlib 的 Python - 重用绘图函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆