Code Monkey home page Code Monkey logo

Comments (5)

mdaeron avatar mdaeron commented on July 20, 2024

I think the default target user should be be someone who doesn't know/care about Python code, so these functions should by default create a new figure and save it to a pdf file. There should be an option no not save it to a file but return the new figure (for those wishing to further modify the figure before saving) and an option to not create a new figure but instead return the newly created Axes() instance (for those wishing to include the plot in a larger, more complex figure).

Something like this should fit the bill (needs more code to create enclosing directories if they don't exist yet)

import numpy as np
from matplotlib import pyplot as ppl


def foo(output = 'fig', savefig = 'foo.pdf'):
	if output == 'fig':
		fig = ppl.figure()
	ax = ppl.subplot(111)
	x = np.linspace(0,10)
	y = np.sin(x)
	ppl.plot(x, y, 'r-', lw = 2)
	if output == 'fig':
		if savefig:
			ppl.savefig(savefig)
		return fig
	elif output == 'ax':
		return ax

If that seems suitable, the next thing to do is to check that all plotting functions follow this template.

from d47crunch.

japhir avatar japhir commented on July 20, 2024

(needs more code to create enclosing directories if they don't exist yet)

Do you mean if you would specify savefig = "bar/baz/foo.pdf" ? Or should it create the figure in a subdirectory (parameter?) by default, as is currently done for e.g. plot_sessions:

	def plot_sessions(self, dir = 'output', figsize = (8,8)):
		'''
		Generate session plots and save them to disk.

		**Parameters**

		+ `dir`: the directory in which to save the plots
		+ `figsize`: the width and height (in inches) of each plot
		'''
		if not os.path.exists(dir):
			os.makedirs(dir)

I also thought the axes creation should happen within the elif, right?

import numpy as np
from matplotlib import pyplot as ppl


def foo(output = 'fig', savefig = 'foo.pdf'):
	if output == 'fig':
		fig = ppl.figure()
	x = np.linspace(0,10)
	y = np.sin(x)
	ppl.plot(x, y, 'r-', lw = 2)
	if output == 'fig':
		if savefig:
			ppl.savefig(savefig)
		return fig
	elif output == 'ax':
 		ax = ppl.subplot(111)  # moved this down here
		return ax

from d47crunch.

mdaeron avatar mdaeron commented on July 20, 2024

The path issues can be simplified:

from os import makedirs
from pathlib import Path
makedirs(Path('foo/bar/baz.txt').parent)
# creates ./foo and/or ./foo/bar if they do not exist yet

The ax should be created before plotting anything (calling it again is likely to delete previously existing plots). Alternatively, don't define ax and simply return ppl.gca() ("get current axes").

The implementation is straightforward; what matters is to define the optimal user-facing behavior. It seems to me that a single parameter covering both save directory and filename is simpler than the existing parameters.

from d47crunch.

japhir avatar japhir commented on July 20, 2024

Hmm I'm still undecided, but I do think splitting the filename from the directory arguments might be more intuitive to some users. Or maybe even set one image_directory variable or something so that all plots are put there? This would allow you to use the same output directory for multiple figures without re-typing but still allow you to use different filenames...

Perhaps the directory argument should be nil and default to the current working directory. It would be nice if it would also support absolute paths (e.g. /home/user/japhir/Pictures/nicefigurefromD47crunch.pdf should work?)

from d47crunch.

timpol avatar timpol commented on July 20, 2024

Sorry to stick my oar in, but for what it's worth, my preference would be for something like this:

from matplotlib import pyplot as ppl

def foo(ax=None, figname=None):

    # data generated by foo
    x = (1, 2, 3)
    y = (1, 4, 9)

    if ax is not None:
        # Plot data on user supplied ax; do not return anything.
        ax.plot(x, y)
    else:
        fig, ax = ppl.subplot(111)
        ax.plot(x, y)
        if figname is not None:
            ppl.savefig(figname)
        # Always return fig. If user only wants it saved to disk, then they
        # don't have to assign the function output to anything when calling foo.
        return fig

from d47crunch.

Related Issues (15)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.