How to resize a Python matplotlib.pyplot.figure already created - python

I'm working with this custom Py visual in PowerBI. Unfortunately, Power BI has some Python code leading my code that pre-defines the image size (5.55555555555556,4.16666666666667).
The result is a small image surrounded by a lot of empty space:
Is there any way I can redefine the size of the image, even though I cannot modify the leading code?
Any other suggestions are welcome,
Thanks!
# Prolog - Auto Generated #
import os, uuid, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
import pandas
os.chdir(u'C:/Users/USER/PythonEditorWrapper_443a6d71-c4cc-4e62-ac6f-2dad3eeace3d')
dataset = pandas.read_csv('input_df_d2b6d8be-2212-4ece-902c-f85219eff22b.csv')
matplotlib.pyplot.figure(figsize=(5.55555555555556,4.16666666666667), dpi=72)
matplotlib.pyplot.show = lambda args=None,kw=None: matplotlib.pyplot.savefig(str(uuid.uuid1()))
#My code starts here, I cannot modify anything above this line.
#I wish I could add a line here to redefine figsize=(5.55555555555556,4.16666666666667)

from matplotlib import pyplot as plt
plt.figure(figsize=(15,20))
try this

Related

jupyter notebook won't show images

#%%
from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()
and
#%%
inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)
plt.figure()
plt.title('inspected')
plt.imshow(inspected)
plt.show()
note config.data.inspected_image_path and config.data.reference_image_path are valid paths.
No errors appear, but no images are shown as well.
Running the same code from a python file does show the image.
I have something missing from the notebook.
This happens both when running using jupyter notebook and directly from PyCharm (pro)
How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.
I don't mind a cv2 solution as well.
You need to set a matplotlib backend.
You can do this with
%matplotlib inline
If you want to be able to interact with the plot, use
%matplotlib notebook

Seaborn displays different color for different run

I followed the setting from here to make matplotlib/seaborn available to display in Zeppelin. However, with the following code:
%python
import seaborn as sns
import matplotlib
import numpy as np
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcdefaults()
import StringIO
def show(p):
img = StringIO.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print "%html <div style='width:600px'>" + img.buf + "</div>"
""" Prepare your plot here ... """
# Use the custom show function instead of plt.show()
x = np.random.randn(100)
ax = sns.distplot(x)
show(sns.plt)
It is strange that the displayed figure show the desired lightblue color the first time I run the code but will display different colors if I execute the same piece of code. Is there a way to force seaborn to keep constant color being displayed? Thanks.
It's not entirely clear what is meant by "running a second time".
However you may try to actually close the figure before running it again. E.g.
plt.close("all")
in order to make sure, a new figure is created which should have the same default color every time.

Ipython notebook (jupyter),opencv (cv2) and plotting?

Is there a way to use and plot with opencv2 with ipython notebook?
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things within the notebook. Easy, just use magic:
%matplotlib inline
Later, I wanted to perform manipulations with interactive plots but plotting in a dedicated window would always freeze. Fine, I learnt again that you need to use magic. Instead of just importing the modules:
%pylab
Now I have moved onto working with opencv. I am now back to the same problem, where I either want to plot inline or use dedicated, interactive windows depending on the task at hand. Is there similar magic to use? Is there another way to get things working? Or am I stuck and need to just go back to running a program from IDLE?
As a side note: I know that opencv has installed correctly. Firstly, because I got no errors either installing or importing the cv2 module. Secondly, because I can read in images with cv2 and then plot them with something else.
This is my empty template:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
%matplotlib inline
im = cv2.imread('IMG_FILENAME',0)
h,w = im.shape[:2]
print(im.shape)
plt.imshow(im,cmap='gray')
plt.show()
See online sample
For a Jupyter notebook running on Python 3.5 I had to modify this to:
import io
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = io.BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
There is also that little function that was used into the Google Deepdream Notebook:
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
from cStringIO import StringIO
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
Then you can do :
img = cv2.imread("an_image.jpg")
And simply :
showarray(img)
Each time you need to render the image in a cell

matplotlib.pyplot.draw() and matplotlib.pyplot.show() have no effect

In the past I was able to do simple animations with matplotlib with a for loop, but this hasn't worked for some time now.
The standard answer is that you have to turn interactive mode on and/or force a redraw with matplotlib.pyplot.draw(). Here is my minimal working example:
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as mplot
mplot.ion()
fig = mplot.figure(1)
ax = fig.add_subplot(111)
for ii in np.arange(0,10):
x = 200*np.random.rand(30)
ax.plot(x)
mplot.draw()
filename = ("img_%d.png" % ii)
mplot.savefig(filename)
When I run this in Interactive Python Editor, I get one figure at the very end with all the plots in it (this also happens with mplot.show())
When I run this in IPython 3.1 (with Python 3.3.5) from the command line, I get nothing at all.
The mplot.savefig(filename) line does seem to work, as the images are generated.
(It's possible this is a bug in the Qt4 backend.)
Try deleting the line matplotlib.use('Qt4Agg'). Works for me. Also works with matplotlib.use('TkAgg'). So it is a backend problem. There is another way to do animations.

Is there any way to ask Basemap not show the plot?

I am trying to use mpl_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen.
My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X Display, is $DISPLAY set properly?'
Is there any way I can avoid the plot to be shown when I use a Basemap function on it?
I just want to save it to a file so later I can read it externally.
My code is:
from mpl_toolkits.basemap import Basemap
import numpy as np
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))
Use the Agg backend, it doesn't require a graphical environment:
Do this at the very beginning of your script:
import matplotlib as mpl
mpl.use('Agg')
See also the FAQ on Generate images without having a window appear.
The easiest way is to put off the interactive mode of matplotlib.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
#NOT SHOW
plt.ioff()
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))

Categories

Resources