My code contains the following lines:
from matplotlib.figure import Figure
figure = Figure(figsize=(10, 5), dpi=dpi)
How can I get matplotlib to show this figure? I also show it embedded in tkinter, which workes fine. However I would also be able to show it in the standard matplotlib window. But I can't for the life of me get it to work.
According to AttributeError while trying to load the pickled matplotlib figure, a simple workaround is:
fig = plt.Figure(...)
......
managed_fig = plt.figure(...)
canvas_manager = managed_fig.canvas.manager
canvas_manager.canvas.figure = fig
fig.set_canvas(canvas_manager.canvas)
Note that I encountered "'Figure' object has no attribute '_original_dpi'" in my environment. Not sure if it's some compatibility issue between my PyPlot and the PyQt5. Just did a hack:
fig._original_dpi = 60
to get around this. Not sure if there are any better solutions.
I usually use matplotlib's pyplot for immediate generation (or produce images in jupyter notebooks). This would look like the following:
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(10, 5), dpi=dpi)
plt.show()
This shows the (blank) figure as desired.
Related
I am working on a project that involves generating a matplotlib animation using pyplot.imshow for the frames. I am doing this in a jupyter notebook. I have managed to get it working, but there is one annoying bug (or feature?) left. After the animation is created, Jupyter shows the last frame of the animation in the output cell. I would like the output to include the animation, captured as html, but not this final frame. Here is a simple example:
import numpy as np
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
I can use the capture magic, but that suppresses everything. This would be OK, but my final goal is to make this public, via binder, and make it as simple as possible for students to use.
I have seen matplotlib animations on the web that don't seem to have this problems, but those used plot, rather than imshow, which might be an issue.
Any suggestions would be greatly appreciated.
Thanks,
David
That's the answer I got from the same thing I was looking for in 'jupyter lab'. Just add plt.close().
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
plt.close() # update
Here's how to create a "stateful" plot in matplotlib and show it in non-interactive mode:
import matplotlib.pyplot as plt
plt.plot([1,2,8])
plt.show()
I am more interested in the "stateless" approach as I wish to embed matplotlib in my own python library. The same plot can be constructed "statelessly" as follows:
from matplotlib.figure import Figure
fig = Figure()
ax = fig.subplots()
lines = ax.plot([1,2,8])
However I don't know how to show it without resorting to pyplot , which I don't want to do as I would like to build up my own display mechanism.
How do I show the figure without resorting to pyplot?
While doing some practice problems using seaborn and a Jupyter notebook, I realized that the distplot() graphs did not have the darker outlines on the individual bins that all of the sample graphs in the documentation have. I tried creating the graphs using Pycharm and noticed the same thing. Thinking it was a seaborn problem, I tried some hist() charts using matplotlib, only to get the same results.
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
plt.hist(titanic['fare'], bins=30)
yielded the following graph:
Finally I stumbled across the 'edgecolor' parameter on the plt.hist() function, and setting it to black did the trick. Unfortunately I haven't found a similar parameter to use on the seaborn distplot() function, so I am still unable to get a chart that looks like it should.
I looked into changing the rcParams in matplotlib, but I have no experience with that and the following script I ran seemed to do nothing:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 1
mpl.rcParams['lines.color'] = 'black'
mpl.rcParams['patch.linewidth'] = 1
mpl.rcParams['patch.edgecolor'] = 'black'
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['axes.edgecolor'] = 'black'
I was just kind of guessing at the value I was supposed to change, but running my graphs again showed no changes.
I then attempted to go back to the default settings using mpl.rcdefaults()
but once again, no change.
I reinstalled matplotlib using conda but still the graphs look the same. I am running out of ideas on how to change the default edge color for these charts. I am running the latest versions of Python, matplotlib, and seaborn using the Conda build.
As part of the update to matplotlib 2.0 the edges on bar plots are turned off by default. However, you may use the rcParam
plt.rcParams["patch.force_edgecolor"] = True
to turn the edges on globally.
Probably the easiest option is to specifically set the edgecolor when creating a seaborn plot, using the hist_kws argument,
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
For matplotlib plots, you can directly use the edgecolor or ec argument.
plt.bar(x,y, edgecolor="k")
plt.hist(x, edgecolor="k")
Equally, for pandas plots,
df.plot(kind='hist',edgecolor="k")
A complete seaborn example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.randn(100)
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
plt.show()
As of Mar, 2021 :
sns.histplot(data, edgecolor='k', linewidth=2)
work.
Using hist_kws=dict(edgecolor="k", linewidth=2) gave an error:
AttributeError: 'PolyCollection' object has no property 'hist_kws'
Using the available styles in seaborn could also solve your problem.
Available styles in seaborn are :
ticks
dark
darkgrid
white
whitegrid
In the following example code...
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('multipage_pdf.pdf') as pdf:
for i in range(10):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter([0, 1, 2], [0, 1, 2])
pdf.savefig()
plt.close()
... every single plot pops up a windows with the actual canvas. Is there an elegant solution to skip the actual drawing of the canvas on the screen and draw the plot directly into a multipage pdf?
PS: Problem only caused when running code within spyder, so related to spyder and not to anything else. Running code directly using python does not cause this popping up of windows.
I think what you are looking for is to clear the figure.
first_page = plt.figure(figsize=(11.69, 8.27))
first_page.clf()
Check out the documentation:
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.clf.html
Some examples:
https://www.programcreek.com/python/example/102298/matplotlib.pyplot.clf
The problem did not arise from matplotlib or anything similar, but just running the code from within Spyder caused this problem. Running the code using python directly does not cause the issues I had before.
I am trying to use the ipython in canopy with matplotlib to prepare graphs (backend set to qt). I wrote the following code line by line int the terminal
import matplotlib.pyplot as plt
fig = plt.figure()
s = fig.add_subplot(1,1,1)
after the second line I can see the figure being made. However after the third line I do not see the sub plot being created. However If I print fig, the sub-plot is can be seen both inline and in the figure window created. This sub-plot also magically appears if I try to zoom. Similar thing happens every time i plot something on the figure. The old version is displayed till I either print the figure or if i try to modify the view using the GUI tools. This is really annoying. It would be great if someone could tell me where the problem is.
Edit: Tried using fig.show() which does not work. Also when I use the plt.plot() directly, there seems to be no problem. The problem comes only when i use fig or any of its subplots
type:
fig.show() when you need to update it.
you should try using fig.canvas.draw() instead of using fig.show() when it comes to interactive plots.
import matplotlib.pyplot as plt
fig = plt.figure()
fig.show()
## should show an empty figure ##
s = fig.add_subplot(1,1,1)
fig.show()
## things stay unchanged ##
fig.canvas.draw()
## things should be OK now ##