First time here and newbie so please bear with me.
I'm following along a data viz tutorial with matplotlib. I'm getting the same results (go me) but the font used (in the plot legend in particular) and the default co lours are different and no parameter has been set to change them. And of course the tutorial's stuff looks much nicer. I don't know why this happens but I'm thinking that maybe I did change some of the stuff in unrelated notebooks and those choices stuck. If so, how do I "reset" please?
I am not allowed to attach screenshots yet. Basically, my plot lines are light blue and orange while his are the traditional discrete dark blue and green. My legend font looks like bad excel while his looks like LateX.
Thank you for your suggestions.
There are a number of ways you can do this and they vary depending on the specific use case but the one I use most often is
from matplotlib import rcParams, rcParamsDefault
rcParams.update(rcParamsDefault)
Although it is likely the case that the tutorial is using a style other than the default so I wouldn't necessarily expect this to make your output look exactly like the tutorial. When using LaTex with matplotlib I use
pgf_with_latex = {
"text.usetex": True,
"pgf.rcfonts": False,
"pgf.preamble": [
r'\usepackage{color}'
]
}
rcParams.update(pgf_with_latex)
You can find more information here regarding customization and here regarding using LaTex with matplotlib.
To find all the built in matplotlib themes, use
plt.style.available
I think the normal one is 'default'. So add this before you make your plots:
plt.style.use(['default'])
But you can make your plots look even better than the tutorial by using some of the other ones.
Related
I am using Bokeh to plot my research study data. I use the log scale a lot. But by default, the axis label of the log axis is shown like 10^2, instead of a superscript 2. The example plot from the Reference doc is exactly so: https://docs.bokeh.org/en/latest/docs/gallery/logaxis.html
I have checked answers to similar questions, and it seems one can use Latex to format the label (https://github.com/bokeh/bokeh/issues/6031). But the solution seems too complicated and it is hard to find out exactly how.
I wonder if there is a simple solution to this issue.
Thanks for any help.
Note from maintainers: Initial built in LaTeX support was added in version 2.4, see this new answer https://stackoverflow.com/a/69198542/3406693
LaTeX can be used to add a label on top of the existing plot. Right now, it cannot be used for axes' titles.
However, the comment from the issue that you've linked attempts to solve it in a different way - by just using special superscript symbols.
Here's my attempt to make that solution shorter and easier to read:
p.yaxis[0].formatter = FuncTickFormatter(code="""
return 10 + (Math.log10(tick).toString()
.split('')
.map(function (d) { return d === '-' ? '⁻' : '⁰¹²³⁴⁵⁶⁷⁸⁹'[+d]; })
.join(''));
""")
As of Bokeh 2.0, passing y_axis_type="log" to figure automatically displays exponents on log axes in a nice way:
For more complicated scenarios, Bokeh 2.4 adds support for LaTeX (and MathML) to some elements in Bokeh, including axis labels. You can now use plot.xaxis.axis_label = r"$$10^2$$", for example (using MathJax delimiters).
Currently, you can use LaTeX on axis labels, tick labels, div widgets, and paragraph widgets. LaTeX support for more elements should be added soon. For more information about the new math text feature and how to use them, see the Bokeh 2.4 release blogpost, the new blackbody radiation example, and the Bokeh user guide!
I'm just wondering if it exists an equivalent to the Matlab figure window in Python where we can modify plots directly from the figure window, or add some features (text, box , arrow, and so on), or make curve fitting, etc.
Matplotlib is good, but it is not as high-level as the Matlab figure. We need to code everything and if we want to modify plots, we need to modify the code directly (except for some basic stuffs like modifing the line color)
With matplotlib, you will indeed remain in the "code it all" workflow. This is not directly the answer you expect but the matplotlib documentation recently gained a very instructive figure that will probably help you if you stay with matplotlib: http://matplotlib.org/examples/showcase/anatomy.html shows the "anatomy" of the figure with all the proper designations for the parts of the figure.
Overall, I could always find examples of what I needed in their excellent gallery http://matplotlib.org/gallery.html
In my opinion, you'll save time by coding these customizations instead of doing them by hand. You may indeed feel otherwise but if not there is a ton of examples of matplotlib code on SO, in their docs and a large community of people around it :-)
Take this page, for example, a sample of which is posted below:
It has matplotlib examples with gray background and more subtle coloring, but when I'm running the same examples, I get the more traditionally colored plots with white background and strong colors. This also seems to be the style used in the pandas documentation.
How can I change the default style locally to match their style?
If you read through the page you linked, just above the Plotting in Pandas section is the following line:
If you want to make your plots look pretty like mine, steal the matplotlibrc file from Huy Nguyen.
In the post is a link to this gist, which contains the matplotlibrc file. Make sure you read through the whole thing and customize it, as for example he has MacOSX as his backend, which you may want to change.
To use the file, save it as ~/.matplotlib/matplotlibrc and restart any running instances of IPython. Your plots should now look prettier :)
As MattDMo mentioned, using a sane matplotlibrc really helps.
The book "Probabilistic-Programming-and-Bayesian-Methods-for-Hackers" also uses a nice matplotlibrc. See this for some examples.
Recently I'm using the package seaborn instead of a custom matplotlibrc not only because it makes my plots look great, but also because it adds some functionality for visualizing distributions, linear models and time series.
I have been running into the problem of generating publication 'perfect' images in Matplotlib (i.e changing the fontsize, marker size, figuresize, number of ticks etc...).
Essentially, I want to do what is described here: http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples except after the figure has already been made. i.e I want to make a function that accepts the Figure object, and makes all the necessary changes, some of which are available as input arguments. That way I don't have to always modify my scripts when I decide to use a figure in a paper.
Is there an efficient way to achieve this?
Note I'm usually using Ipython.
Well, we are doing this all the time to create good figures. In our case we wanted something that would automatically choose the linestyle and marker because we always have to plot many lines in the same figure, and this would avoid manually specifying these things.
We programmed some functions so that at the end you need a plot.py script, which is very simple, and an input.txt with all the info. In the input file you can also use any parameter like linewidth, label, and so forth.... but by default it will follow the pre-defined order for linestyles, markers and so on.
Also, you need a good matplotlibrc file. You can have many different matplotlibrc files since the highest priority is given to the one at the local directory, as explained here. This will allow you to customize keeping your plotting code cleaner.
The functions commented above (with examples) are available in this link, maybe they can give you some insights.
They solved one problem I had with subplots, described here.
Maybe you can make use of matplotlib pickling available in vs 1.2.1.
As said in the above link:
Philip Elson added an experimental feature to make figures picklable
for quick and easy short-term storage of plots. Pickle files are not
designed for long term storage, are unsupported when restoring a
pickle saved in another matplotlib version and are insecure when
restoring a pickle from an untrusted source. Having said this, they
are useful for short term storage for later modification inside
matplotlib.
No personal experience, however
I have been looking for a way to be able to select which series are visible on a plot, after a plot is created.
I need this as i often have plots with many series. they are too many to plot at the same time, and i need to quickly and interactively select which series are visible. Ideally there will be a window with a list of series in the plot and checkboxes, where the series with the checked checkbox is visible.
Does anyone know if this has been already implemented somewhere?, if not then can someone guide me of how can i do it myself?
Thanks!
Omar
It all depends on how much effort you are willing to do and what the exact requirements are, but you can bet it has already been implemented somewhere :-)
If the aim is mainly to not clutter the image, it may be sufficient to use the built-in capabilities; you can find relevant code in the matplotlib examples library:
http://matplotlib.org/examples/event_handling/legend_picking.html
http://matplotlib.org/examples/widgets/check_buttons.html
If you really want to have a UI, so you can guard the performance by limiting the amount of plots / data, you would typically use a GUI toolbox such as GTK, QT or WX. Look here for some articles and example code:
http://eli.thegreenplace.net/2009/05/23/more-pyqt-plotting-demos/
A list with checkboxes will be fine if you have a few plots or less, but for more plots a popup menu would probably be better. I am not sure whether either of these is possible with matplotlib though.
The way I implemented this once was to use a slider to select the plot from a list - basically you use the slider to set the index of the series that should be shown. I had a few hundred series per dataset, so it was a good way to quickly glance through them.
My code for setting this up was roughly like this:
fig = pyplot.figure()
slax = self.fig.add_axes((0.1,0.05,0.35,0.05))
sl = matplotlib.widgets.Slider(slax, "Trace #", 0, len(plotlist), valinit=0.0)
def update_trace():
ax.clear()
tracenum = int(np.floor(sl.val))
ax.plot(plotlist[tracenum])
fig.canvas.draw()
sl.on_changed(update_trace)
ax = self.fig.add_axes((0.6, 0.2, 0.35, 0.7))
fig.add_subplot(axes=self.traceax)
update_trace()
Here's an example:
Now that plot.ly has opened sourced their libraries, it is a really good choice for interactive plots in python. See for example: https://plot.ly/python/legend/#legend-names. You can click on the legend traces and select/deselect traces.
If you want to embed in an Ipython/Jupyter Notebook, that is also straightforward: https://plot.ly/ipython-notebooks/gallery/