How can i change the existing Bokeh plot ticks size, specifically package that was being used to plot already defined a plot layout of bokeh ? How can i overwrite those layout ? Below is the example code of the plot to reproduce the plot.
# !pip install arlpy
import arlpy.uwapm as pm
import arlpy.plot as plt
env = pm.create_env2d()
pm.plot_env(env, width=900)
Here is the generated figure for which i want to redefined layout.
This is a bit tricky and but it is possible to get it done. But I have to mention that I don't like this solution.
To get a figure you have to enable the hold argument because otherwise it will be plotted immediately and return None. Then you can get the current figure using arlpy.plot.gcf() and set all parameters. To show the figure now you have to use the bokeh call show because the figure is a bokeh object now and in arlpy it is not available to set the hold to False again and show the figure. In fact the figure is now waiting for some data to add.
Here is an example.
from bokeh.plotting import figure, show
import arlpy.plot
arlpy.plot.figure(title='Demo 1', width=500)
arlpy.plot.plot([0,10], [0,10], hold=True)
p = arlpy.plot.gcf()
p.axis.major_tick_line_width = 3
show(p)
Unfortunately I found no solution where I use import arlpy.uwapm as pm because there is no return parameter in the plot_envfunction. So you can`t get the figure and make some changes.
I hope this helps. But I guess it is not satisfying.
I'm getting a bit confused around the concepts of axes, and frankly - what modifies what when it comes to the matplotlib backend. I was told in this post that "whenever you first do something that requires an axes object, one is created for you and becomes the default object that all of your future actions will be applied to until you change the current axes to something else."
But why is it, then, that figsize doesn't seem to do anything when I use the following code in the same cells in a Jupyter notebook:
dataset[['TV','radio']].plot()
plt.figure(figsize=(5,10))
and also
dataset.hist()
plt.figure(figsize=(10,20))
Why don't either of these work? How can I tell which axes object I'm referencing? Thanks so much
The problem is that plt.figure creates a new figure.
If you want to resize the existing figure use this:
dataset[['TV','radio']].plot()
fig = plt.gcf() # gcf: get current figure
fig.set_size_inches(5,10)
Another way you could do it -- that's illustrative of how axes get created and later used -- is to start off with the figure size like this:
import numpy as np, pandas as pd
df = pd.DataFrame({'x':[np.random.randint(0,10) for i in range(10)]})
fig = plt.figure(figsize=(5,5))
ax = fig.gca() # gca: get current axes
df.plot(ax=ax)
Result:
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
f_name = font_manager.FontProperties(fname='C:/Windows/Fonts/HANBatangExt.ttf').get_name()
rc('font', family=f_name)
뛰기운동
plt.plot(run_before, run_after, 'ro-')
걷기운동
plt.plot(walk_before, walk_after, 'bo-')
plt.figure(figsize=((10,8)))
plt.show()
It is not an error but the output you see is due to the fact that you have used
plt.figure(figsize=((10,8)))
after plt.plot. Therefore, you first get a figure on you screen and a figure object is created by plt.figure. To get rid of it, you should first set the figure size before plotting, something like this:
plt.figure(figsize=((10,8)))
plt.plot(run_before, run_after, 'ro-')
plt.plot(walk_before, walk_after, 'bo-')
plt.show()
There are other ways to set the figure size after plotting but since your code is fine enough, you are good to go with the above modification.
It's not an Error it shows your figure dimensions. If you want to get rid of it try using rcParams parameter
plt.rcParams["figure.figsize"] = (10,8)
It is not the error just a message that an image file is returned
If you are using the VS_code then
Click on the left side little code icon
Select Image/Png option this will make your graph visible
If you havent seleced the Image/Png option then you might not be able to see the output
At the moment I am working with Spyder and doing my plotting with matplotlib. I have two monitors, one for development and another for (data) browsing and other stuff. Since I am doing some calculations and my code often changes, I often (re)execute the code and have a look at the plots to check if the results are valid.
Is there any way to place my matplotlib plots on a second monitor and refresh them from the main monitor?
I have already searched for a solution but could not find anything. It would be really helpful for me!
Here's some additional information:
OS: Ubuntu 14.04 (64 Bit)
Spyder-Version: 2.3.2
Matplotlib-Version: 1.3.1.-1.4.2.
I know it's an old question but I came across a similar problem and found this question. I managed to move my plots to a second display using the QT4Agg backend.
import matplotlib.pyplot as plt
plt.switch_backend('QT4Agg')
# a little hack to get screen size; from here [1]
mgr = plt.get_current_fig_manager()
mgr.full_screen_toggle()
py = mgr.canvas.height()
px = mgr.canvas.width()
mgr.window.close()
# hack end
x = [i for i in range(0,10)]
plt.figure()
plt.plot(x)
figManager = plt.get_current_fig_manager()
# if px=0, plot will display on 1st screen
figManager.window.move(px, 0)
figManager.window.showMaximized()
figManager.window.setFocus()
plt.show()
[1] answer from #divenex: How do you set the absolute position of figure windows with matplotlib?
This has to do with matplotlib, not Spyder. Placing the location of a figure explicitly appears to be one of those things for which there's really just workarounds ... see the answers to the question here. That's an old question, but I'm not sure there's been change since then (any matplotlib devs, feel free to correct me!).
The second monitor shouldn't make any difference, it sounds like the issue is just that the figure is being replaced with a new one.
Fortunately you can update figures you've moved to where you want them pretty easily, by using the object interface specifically, and updating the Axes object without creating a new figure. An example is below:
import matplotlib.pyplot as plt
import numpy as np
# Create the figure and axes, keeping the object references
fig = plt.figure()
ax = fig.add_subplot(111)
p, = ax.plot(np.linspace(0,1))
# First display
plt.show()
# Some time to let you look at the result and move/resize the figure
plt.pause(3)
# Replace the contents of the Axes without making a new window
ax.cla()
p, = ax.plot(2*np.linspace(0,1)**2)
# Since the figure is shown already, use draw() to update the display
plt.draw()
plt.pause(3)
# Or you can get really fancy and simply replace the data in the plot
p.set_data(np.linspace(-1,1), 10*np.linspace(-1,1)**3)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
plt.draw()
I am using pylab in matplotlib to create a plot and save the plot to an image file. However, when I save the image using pylab.savefig( image_name ), I find that the SIZE image saved is the same as the image that is shown when I use pylab.show().
As it happens, I have a lot of data in the plot and when I am using pylab.show(), I have to maximize the window before I can see all of the plot correctly, and the xlabel tickers don't superimpose on each other.
Is there anyway that I can programmatically 'maximize' the window before saving the image to file? - at the moment, I am only getting the 'default' window size image, which results in the x axis labels being superimposed on one another.
There are two major options in matplotlib (pylab) to control the image size:
You can set the size of the resulting image in inches
You can define the DPI (dots per inch) for output file (basically, it is a resolution)
Normally, you would like to do both, because this way you will have full control over the resulting image size in pixels. For example, if you want to render exactly 800x600 image, you can use DPI=100, and set the size as 8 x 6 in inches:
import matplotlib.pyplot as plt
# plot whatever you need...
# now, before saving to file:
figure = plt.gcf() # get current figure
figure.set_size_inches(8, 6)
# when saving, specify the DPI
plt.savefig("myplot.png", dpi = 100)
One can use any DPI. In fact, you might want to play with various DPI and size values to get the result you like the most. Beware, however, that using very small DPI is not a good idea, because matplotlib may not find a good font to render legend and other text. For example, you cannot set the DPI=1, because there are no fonts with characters rendered with 1 pixel :)
From other comments I understood that other issue you have is proper text rendering. For this, you can also change the font size. For example, you may use 6 pixels per character, instead of 12 pixels per character used by default (effectively, making all text twice smaller).
import matplotlib
#...
matplotlib.rc('font', size=6)
Finally, some references to the original documentation:
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig, http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.gcf, http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.set_size_inches, http://matplotlib.sourceforge.net/users/customizing.html#dynamic-rc-settings
P.S. Sorry, I didn't use pylab, but as far as I'm aware, all the code above will work same way in pylab - just replace plt in my code with the pylab (or whatever name you assigned when importing pylab). Same for matplotlib - use pylab instead.
You set the size on initialization:
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!
Edit:
If the problem is with x-axis ticks - You can set them "manually":
fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here
And so on with other aspects of Your plot. You can configure it all. Here's an example:
from numpy import arange
import matplotlib
# import matplotlib as mpl
import matplotlib.pyplot
# import matplotlib.pyplot as plt
x1 = [1,2,3]
y1 = [4,5,6]
x2 = [1,2,3]
y2 = [5,5,5]
# initialization
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # The size of the figure is specified as (width, height) in inches
# lines:
l1 = fig2.add_subplot(111).plot(x1,y1, label=r"Text $formula$", "r-", lw=2)
l2 = fig2.add_subplot(111).plot(x2,y2, label=r"$legend2$" ,"g--", lw=3)
fig2.add_subplot(111).legend((l1,l2), loc=0)
# axes:
fig2.add_subplot(111).grid(True)
fig2.add_subplot(111).set_xticks(arange(1,3,0.5))
fig2.add_subplot(111).axis(xmin=3, xmax=6) # there're also ymin, ymax
fig2.add_subplot(111).axis([0,4,3,6]) # all!
fig2.add_subplot(111).set_xlim([0,4])
fig2.add_subplot(111).set_ylim([3,6])
# labels:
fig2.add_subplot(111).set_xlabel(r"x $2^2$", fontsize=15, color = "r")
fig2.add_subplot(111).set_ylabel(r"y $2^2$")
fig2.add_subplot(111).set_title(r"title $6^4$")
fig2.add_subplot(111).text(2, 5.5, r"an equation: $E=mc^2$", fontsize=15, color = "y")
fig2.add_subplot(111).text(3, 2, unicode('f\374r', 'latin-1'))
# saving:
fig2.savefig("fig2.png")
So - what exactly do You want to be configured?
I think you need to specify a different resolution when saving the figure to a file:
fig = matplotlib.pyplot.figure()
# generate your plot
fig.savefig("myfig.png",dpi=600)
Specifying a large dpi value should have a similar effect as maximizing the GUI window.
Check this:
How to maximize a plt.show() window using Python
The command is different depending on which backend you use. I find that this is the best way to make sure the saved pictures have the same scaling as what I view on my screen.
Since I use Canopy with the QT backend:
pylab.get_current_fig_manager().window.showMaximized()
I then call savefig() as required with an increased DPI per silvado's answer.
You can look in a saved figure it's size, like 1920x983 px (size when i saved a maximized window), then I set the dpi as 100 and the size as 19.20x9.83 and it worked fine. Saved exactly equal to the maximized figure.
import numpy as np
import matplotlib.pyplot as plt
x, y = np.genfromtxt('fname.dat', usecols=(0,1), unpack=True)
a = plt.figure(figsize=(19.20,9.83))
a = plt.plot(x, y, '-')
plt.savefig('file.png',format='png',dpi=100)
I had this exact problem and this worked:
plt.savefig(output_dir + '/xyz.png', bbox_inches='tight')
Here is the documentation:
[https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html][1]
I did the same search time ago, it seems that he exact solution depends on the backend.
I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python
I adjusted the code and ended up with the function below.
It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.
Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.
def maximize(backend=None,fullscreen=False):
"""Maximize window independently on backend.
Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
if backend is None:
backend=matplotlib.get_backend()
mng = plt.get_current_fig_manager()
if fullscreen:
mng.full_screen_toggle()
else:
if backend == 'wxAgg':
mng.frame.Maximize(True)
elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
mng.window.showMaximized()
elif backend == 'TkAgg':
mng.window.state('zoomed') #works fine on Windows!
else:
print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
plt.show()
plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)
Old question but to anyone in need, Here's what had worked for me a while ago:
You have to have a general idea of the aspect ratio that would maximise your plot fitting. This will take some trial and error to get right, but generally 1920x1080 would be a good aspect ratio for most modern monitors. I would still suggest playing around with the aspect ratios to best suit your plot.
Steps:
Before initiating the plot, set the size for the plot, use:
plt.figure(19.20, 10.80)
**notice how I have multiplied my aspect ratio by '0.01'.
At the end of the plot, when using plt.savefig, save it as follows:
plt.savefig('name.jpg', bbox_inches='tight', dpi=1000)
If I understand correctly what you want to do, you can create your figure and set the size of the window. Afterwards, you can save your graph with the matplotlib toolbox button. Here an example:
from pylab import get_current_fig_manager,show,plt,imshow
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_geometry("500x500+0+0")
#in this case 500 is the size (in pixel) of the figure window. In your case you want to maximise to the size of your screen or whatever
imshow(your_data)
show()