seaborn rc parameters for set_context and set_style - python

In the tutorial for setting up the aesthetics of your plots, there are a few different methods:
set_style
set_context
axes_style
Each one of these accepts an rc keyword parameter dictionary. In each individual API page for the above three functions, it says:
rcdict, optional:
Parameter mappings to override the values in the preset seaborn style dictionaries. This only updates parameters that are considered part of the style definition.
Back in the tutorial page, under axes_style it goes on to say exactly how you can see what parameters are available for the rc dictionary for this one function:
If you want to see what parameters are included, you can just call the function with no arguments, which will return the current settings:
However, using this on the other functions always returns None. So, for example, I am using the following mix of matplotlib and seaborn
to set parameters:
mpl.rcParams['figure.figsize'] = [16,10]
viz_dict = {
'axes.titlesize':18,
'axes.labelsize':16,
}
sns.set_context("notebook", rc=viz_dict)
sns.set_style("whitegrid")
I also noticed that putting my dictionary in the set_style method does nothing, while, at least for those parameters, it only works in set_context. This means that they each have mutually exclusively characteristics that can be edited. However, this is not outlined anywhere in the docs.
I want to know which one of these three functions will accept a parameter for figsize. I'd also be curious to see what else they accept that might help me fine-tune things. My goal is to exclusively use the seaborn interface as often as possible. I don't need the fine tune control of things matplotlib provides, and often find it awkward anyway.

It would appear that the answer is 'none of the above'. The valid keys for set_style and set_context are listed here:
_style_keys = [
"axes.facecolor", "axes.edgecolor",
"axes.grid", "axes.axisbelow", "axes.labelcolor",
"figure.facecolor", "grid.color",
"grid.linestyle", "text.color",
"xtick.color", "ytick.color",
"xtick.direction", "ytick.direction",
"lines.solid_capstyle",
"patch.edgecolor", "patch.force_edgecolor",
"image.cmap", "font.family", "font.sans-serif",
"xtick.bottom", "xtick.top",
"ytick.left", "ytick.right",
"axes.spines.left", "axes.spines.bottom",
"axes.spines.right", "axes.spines.top",]
_context_keys = [
"font.size", "axes.labelsize",
"axes.titlesize", "xtick.labelsize",
"ytick.labelsize", "legend.fontsize",
"axes.linewidth", "grid.linewidth",
"lines.linewidth", "lines.markersize",
"patch.linewidth",
"xtick.major.width", "ytick.major.width",
"xtick.minor.width", "ytick.minor.width",
"xtick.major.size", "ytick.major.size",
"xtick.minor.size", "ytick.minor.size",]
Also note that set_style is just a convenience function which calls axes_style.
So you will have to use matplotlib.rcParams, although if the typical rcParams['figure.figsize'] = [16,10] syntax is not amenable you could of course create your own style.

Related

Can anyone explain me seaborn's set_context()?

I am trying to learn visualization with python and stuck here:
sns.set_context('notebook')
ax = data.plot.hist(bins=25, alpha=0.42)
ax.set_xlabel('Size (cm)');
Can anyone help me to explain what does this code sample mean?
From the documentation:
seaborn.set_context(context=None, font_scale=1, rc=None)
Set the
plotting context parameters.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context is
“notebook”, and the other contexts are “paper”, “talk”, and “poster”,
which are version of the notebook parameters scaled by .8, 1.3, and
1.6, respectively.
Parameters: context : dict, None, or one of {paper, notebook, talk,
poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the font
elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are considered
part of the context definition.
sns.set_context('notebook') in your example, sets up a number of parameters which will define how seaborn produces plots you generate using the module.

Python: How do I find / inspect what kind of arguments a function accepts?

I am trying to find out what what kind of arguments a function accepts. This is because I usually am unsure of what arguments a function even accepts in a first place. For example, consider a function from the the package Plotly:
fig.update_xaxes(ticks="outside")
I want to be able to know what are the different arguments ticks could be, i.e. ticks="inside" or ticks=outside.
Ideally the output would be that ticks accepts arguments such as: inside, outside, etc...
I usually get the parts pointed out by the arrows wrong because I don't know what ticks and tickson even accepts in the first place, as well as, what they do.
Right now I am using inspect. But, this doesn't tell me that I can input as arguments.
>>import inspect
>>inspect.getfullargspec(go.Figure.update_xaxes)
>>print(inspect.getsource(go.Figure.update_xaxes))
OUTPUT:
def update_xaxes(self, patch=None, selector=None, row=None, col=None, **kwargs):
"""
Perform a property update operation on all xaxis objects
that satisfy the specified selection criteria
Parameters
----------
patch: dict
Dictionary of property updates to be applied to all
xaxis objects that satisfy the selection criteria.
selector: dict or None (default None)
Dict to use as selection criteria.
xaxis objects will be selected if they contain
properties corresponding to all of the dictionary's keys, with
values that exactly match the supplied values. If None
(the default), all xaxis objects are selected.
row, col: int or None (default None)
Subplot row and column index of xaxis objects to select.
To select xaxis objects by row and column, the Figure
must have been created using plotly.subplots.make_subplots.
If None (the default), all xaxis objects are selected.
**kwargs
Additional property updates to apply to each selected
xaxis object. If a property is specified in
both patch and in **kwargs then the one in **kwargs
takes precedence.
Returns
-------
self
Returns the Figure object that the method was called on
"""
for obj in self.select_xaxes(selector=selector, row=row, col=col):
obj.update(patch, **kwargs)
return self
Using online documentation is always recommended but please keep in mind that documentation is not always generated directly from code or even if auto-generated it can contain errors or be out of date.
If you are using Jupyter Notebook you can get help on any object by running:
help(object)
If you are using an IDE like Eclipse the object options (parameters, etc..) are usually displayed to you as you type in your IDE:
And then when you are using a Figure instance:
Then when you click on it or choose ENTER when highlighting an item the parameters are inserted into your code like this:
In most IDE's you can also push CMD (Mac) or CTRL (Windows) when hovering over the library, function, object or a variable in your code (text changes into a link and the cursor changes to hand) and then click on it to go to its definition.
If the object or function is defined in another file, that file will automatically open in your IDE and the cursor will point to that object/function that you clicked.
In case of:
import plotly.graph_objects as go
fig = go.Figure(data, layout)
clicking on Figure will open _figure.py file and display this code:
I hope this helps.
In the specific case of plotly.graph_objects.Figure.update_xaxes(), you can pass in as a keyword argument anything that is accepted by the constructor of plotly.graph_objects.layout.Xaxis, and we will update the docstring and documentation to make that clearer. Note that plotly.graph_objects.layout.Xaxis accepts in its constructor what we call "magic underscores" meaning that for nested properties like title you can pass in title_font and so on, which are also not explicitly listed in that docstring. This is one of the downsides to having such a dynamic API.

Additional keyword arguments in seaborn jointplot

I'm trying to find out how matplotlib and seaborn plotting functions are associated. Particularly, I'd like to know what pyplot arguments can be passed into keyword dicts marginal_kws and annot_kws in function seaborn.jointplot().
Suppose we have DataFrame data with columns c0 and c1. I guessed that joint_kws accepts arguments from pyplot.hexbin(), so when I tried to tune the appearance with arguments from there, it worked fine:
import seaborn as sns
sns.jointplot('c0', 'c1', data=data, kind='hex',
joint_kws={'gridsize':100, 'bins':'log', 'xscale':'log', 'yscale':'log'})
Then I tried to set log scale at histogram axes with an argument log=True from pyplot.hist():
sns.jointplot('c0', 'c1', data=data, kind='hex',
joint_kws={'gridsize':100, 'bins':'log', 'xscale':'log', 'yscale':'log'},
marginal_kws={'log':True})
This results in
TypeError: distplot() got an unexpected keyword argument 'log'
How to put it right?
P.S. This question is not about setting log scales in seaborn (with JointGrid, i know), but rather about passing matplotlib arguments into seaborn functions as a whole.
The dictionary of keyword arguments gets passed to distplot, which takes a dictionary for hist_kws. So you'll have to do something like marginal_kws={'hist_kws': {'log': True}}. With that said, shared log axes remain an enduring headache with jointplot, and I couldn't get something that looked good out of the box when adapting your code. Some tweaking might get it working, though.
It may also be useful to try and use JointGrid directly to avoid this kind of complexity.

Regarding Function in Python

I am new to Python. I discover that in the arguments of e.g., annotate, it is allow to put xy=..., xytext=...., is it a feature of Python? If yes how do we define a function in python that allow this?
import numpy as np
from matplotlib import pyplot as plt
plt.annotate('Here is something special', xy = (2, 1), xytext=(1,5),arrowprops={'facecolor': 'r'})
This is a python's feature, called keyword parameters.
Functions can also be called using keyword arguments of the form "keyword = value". You can read about this topic in the documentation.
keyword arguments is not different than normal arguments except order isn't important. There is nothing special to do in the definition. For example:
def my_func(a, b):
pass
my_func(1, 2)
my_func(b=2, a=1)
# Both of them get the same results
I'm not sure if I completely understand what you want to do, but I think that this part of the Python documentation might answer your question:
https://docs.python.org/release/1.5.1p1/tut/keywordArgs.html

Custom view with InstanceEditor

I'm working on a dynamic Traits UI where I can select the class to use for certain instances. I've got it working nicely using an InstanceEditor with a "values" argument containing InstanceFactoryChoice instances.
My problem appears when I want to specify a view to use for the selected instance. Using the "view" argument works if I omit the "values" argument, but with it I get the default view instead. The relevant part of the view looks like this:
Item('item',
show_label=False,
editor=InstanceEditor(
view=item_view,
values=[InstanceFactoryChoice(klass=k) for k in classes],
editable=True),
style='custom')
What's more confusing to me is that it also works as expected (i.e. uses the "item_view" view to display the instance) when I use the "simple" style instead of "custom". However, then the view appears in a new window, I want it to be inline.
Am I missing something here? I'm on TraitsUI 4.3.
OK, after some source-diving I found that adding the "view" argument to the InstanceFactoryChoice call instead seems to do what I want. Still, it seems there's an inconsistency in there somewhere...
InstanceFactoryChoice(klass=k, view=item_view)

Categories

Resources