I'm calling the inline mode for IPython Notebook using;
%pylab inline
And the following code plots a figure immediately at the cell;
fig = plt.figure()
axes = fig.add_axes([0, 0, 1, 1])
However I would like to create the plot/axes etc. in one cell, and plot later using maybe;
fig.show()
How do I gain more control of the inline mode? If I don't use %pylab inline, it creates the plot in a seperate window which I don't want (and it usually freezes the window).
Versions;
Numpy: 1.7.0
Matplotlib: 1.2.1rc1
Python: 2.7.2 (default, Jun 24 2011, 12:22:14) [MSC v.1500 64 bit (AMD64)]
Pandas: 0.10.1
PyLab: 1.7.0
So I guess what you want is this:
from matplotlib.backends.backend_agg import FigureCanvasAgg as fc
fig = Figure()
canvas = fc(fig)
ax = fig.add_subplot(1, 1, 1)
ax.plot(arange(10))
To display the plot in another cell simply use:
fig
You might be looking for disabling autoclose figure :
InlineBackend options
---------------------
--InlineBackend.close_figures=<CBool>
Default: True
Close all figures at the end of each cell.
When True, ensures that each cell starts with no active figures, but it also
means that one must keep track of references in order to edit or redraw
figures in subsequent cells. This mode is ideal for the notebook, where
residual plots from other cells might be surprising.
When False, one must call figure() to create new figures. This means that
gcf() and getfigs() can reference figures created in other cells, and the
active figure can continue to be edited with pylab/pyplot methods that
reference the current active figure. This mode facilitates iterative editing
of figures, and behaves most consistently with other matplotlib backends,
but figure barriers between cells must be explicit.
still, IPython will show the figure if the last line of a cell return a fig object, you can avoid that by ending it with a ; or add pass as the last line.
With newer jupyter and matplotlib
Jupyter: 4.6
Jupyter notebook: 6.0
Matplotlib: 3.1
ipykernel: 5.1
all you really need is to create your figure with matplotlib.pyplot.Figure (in one cell) and then make that figure the cell value in another cell. For example
In cell [1]
%matplotlib inline
In cell [2]
from matplotlib.pyplot import Figure
from numpy import arange
from numpy.random import normal
fig = Figure()
ax = fig.add_subplot(111)
ax.plot(arange(10),normal(size=10),label='Data')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.legend();
and finally in cell [3]
fig
That should be enough. See the screenshot below
Note suggestions with matplotlib.pyplot.ioff() and similar does not work
Related
I am quite new to coding and need to create some type of map to display my data.
I have data in an excel sheet showing a list of countries and a number showing amount of certain crimes. I want to show this in a choropleth map.
I have seen lots of different ways to code this but can't seem to get any to correctly read in the data. Will I need to get import country codes into my df?
I have my world map from github and downloaded it in its raw format to my computer and into jupyter notebook.
My dataframe is also loaded, as the excel sheet, in jupyter notebook.
What are the first steps i need to take to load this into a map?
This is the code I have had the most success with:
import pandas as pd
import folium
df = pd.read_excel('UK - Nationality and Type.xlsx')
state_geo = 'countries.json'
m1 = folium.Map(location=[55, 4], zoom_start=3)
m1.choropleth(
geo_data=state_geo,
data=df,
columns=['Claimed Nationality', 'Labour Exploitation'],
key_on='feature.id',
fill_color='YlGn',
fill_opacity=0.5,
line_opacity=0.2,
legend_name='h',
highlight=True
)
m1.save("my_map.html")`
But i just get a big world map, all in the same shade of grey
this is what the countries.json looks like
I'm trying to edit the tick labels but I keep getting scientific notation, even after setting the ticks. Here is a MWE:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(9, 7))
fig.subplots_adjust(left=0.11, right=0.95, top=0.94)
ax.ticklabel_format(style='plain')
plt.plot([1,4],[3,6] )
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xticks([0.7,1,1.5,2,2.5,3,4,5])
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
which produces this plot
As you can see ax.ticklabel_format(style='plain') doesn't seem to work as I keep getting tick labels in scientific notation, and when using ax.set_xticks the old tick labels are still present. I took a look at this topic and it seems like the problem is in the choose of the ticks, if I use for example 0.3 instead of 0.7 as the first tick it works, however I need to do a plot in this specific range and using log scale.
Any work around?
Actually, your code is doing what you need, the problem is the labels from the minor ticks that remain unaffected and overlap with the major ticks
you can simply add the line:
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
full code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(9, 7))
fig.subplots_adjust(left=0.11, right=0.95, top=0.94)
ax.ticklabel_format(style='plain')
plt.plot([1,4],[3,6] )
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xticks([0.7,1,1.5,2,2.5,3,4,5])
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
I currently try to modify a plot in a python2.7 code. This plot come from a radiative transfert code (what I can't modify), and the output is a class type with a method :
plot_image(wavelength0, overplot=False, inclination=None, cmap=None,
ax=None, axes_units='AU', polarization=False, polfrac=False,
psf_fwhm=None, vmin=None, vmax=None, dynamic_range=1000000.0)
more informations here
So, when I put a plt.title() or plt.savefig() just after that, I call the respective method and the title of the plot changes and the plot is saved, as expected!
However, there is two things that I didn't find a way to do it :
Add a colorbar
trace the surface in log-scale
because no arguments in the method allow to do it.
When I try something like plt.colorbar(fig) with fig=res.plot_image(...) (with res the class, output of radiative transfert code) the error said that fig is not a mappable object (seems logic).
Any ideas that could help me ? hope I gave you enough informations.
Sorry for my English
Lo_du
If res.plot_image(...) only plots one image to one axes, the solution to obtain a colorbar might be pretty easy.
import numpy as np
import matplotlib.pyplot as plt
#.... some code
res.plot_image(...)
im, = plt.gca().get_images()
plt.colorbar(im)
plt.show()
I'm trying to wrap my head around using axes-objects in conjunction with a Pandas-dataframe (object df in the following snippet):
import matplotlib.pyplot as plt
fig=plt.figure()
axes=fig.add_subplot(111)
for key, grp in df.groupby(['bondYear', 'bondQuarter']):
axes = grp['priceAvg'].plot(label=key, ax=axes)
This runs through without any complaints, but now I'm looking for a way to actually make my plot show (and later save to *.png like with using savefig()). plt.show() works but opens two windows, one showing my plot and the other one being empty, so that's not it.
Apparently I'm missing something regarding the use of matplotlib, can you help me out?
Many thanks in advance for your help!
You shouldn't reassign your plot to axes, although that should not matter. Try this.
fig, ax = plt.subplots(figsize=(8,6))
for key, grp in df.groupby(['bondYear', 'bondQuarter']):
grp['priceAvg'].plot(label=key, ax=ax)
plt.legend()
plt.show()
plt.savefig('figname.png')
You can also plot them all at once without using iteration doing the following but you are easily able to control the legend.
fig, ax = plt.subplots(figsize=(8,6))
df.groupby(['col1', 'col2']).plot(ax=ax)
I have been able to batch import svg at their appropriate places, through the python scripts that come with the fontforge. Now I want to scale up each glyph let's say 200%. I am able to do that in fontforge through the
Elements->Tranformations->Transform->choosing scale uniformly from
the dropdown and entering 200%.
How can I do the same from the functions provided in the python library, I couldn't find it.
Well Found it myself!
import fontforge
import psMat
SFD_FONT = fontforge.open("DejaVuMono.sfd")
INDEX = 105
SCALE_MATRIX = psMat.scale(0.50)
print SFD_FONT[INDEX].foreground[0].boundingBox()
SFD_FONT[INDEX].foreground[0].transform(SCALE_MATRIX)
print SFD_FONT[INDEX].foreground[0].boundingBox()