I am unable to display images in iPython from matplotlib, an image appears for a split of a second in a pop up window instead of inline and then closes immediately. nothing appears in the iPython console which is inside Spyder.
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slop_and_intercept (xs,ys):
m = ( ((mean(xs)*mean(ys))-mean(xs*ys)) /
((mean(xs)**2)-mean(xs**2)) )
b = mean(ys)-m*mean(xs)
return m,b
m,b = best_fit_slop_and_intercept(xs,ys)
print (m,b)
regression_line = [m*x + b for x in xs ]
print (regression_line)
predict_x = 9
predict_y = predict_x*m + b
plt.scatter(predict_x,predict_y, color = 'g')
plt.scatter(xs,ys)
plt.plot(xs, regression_line)
plt.show()
You can type %matplotlib inline inside the iPython console to generate your plots within the console inside spyder. You can also type %matplotlib qtto get an interactive window.
Your code snippet works for me with both settings. Failing that you can go to [preferences>iPython console>Graphics>Graphics backend] to adjust the graphics defaults and settings to see if that fixes the problem.
Related
I'm trying to share a github repo on binder. Locally, my interactive plot using matplotlib and #interact works ok. On binder it works half way. Same code adds static images to the cell output in binder notebook when slider value changes.
Question: how to fix binder behavior and make an interactive plot?
git repository https://github.com/queezz/Complex_Numbers
My notebook looks like this:
%pylab inline
from ipywidgets import interact, widgets
x = np.linspace(0,np.pi,100)
#interact
def plot_interactive(a=widgets.FloatSlider(min=1, max=10, val=1)):
plot(x,np.sin(x*a))
gca().set_aspect('equal')
ylim(-1.1,1.1)
Screenshot from binder:
Found a good working example:
https://github.com/Kapernikov/ipywidgets-tutorial
The gist of it is to use %matplotlib widget and #widgets.interact.
It seems that usage of %pylab inline is discouraged now, see this git issue.
I copy a part of the code from the tutorial which produces the same result as wanted in the question.
%matplotlib widget
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
# set up plot
fig, ax = plt.subplots(figsize=(6, 4))
ax.set_ylim([-4, 4])
ax.grid(True)
# generate x values
x = np.linspace(0, 2 * np.pi, 300)
def my_sine(x, w, amp, phi):
"""
Return a sine for x with angular frequeny w and amplitude amp.
"""
return amp*np.sin(w * (x-phi))
#widgets.interact(w=(0, 10, 1), amp=(0, 4, .1), phi=(0, 2*np.pi+0.01, 0.01))
def update(w = 1.0, amp=1, phi=0):
"""Remove old lines from plot and plot new one"""
[l.remove() for l in ax.lines]
ax.plot(x, my_sine(x, w, amp, phi), color='C0')
I wasn't able to get #queez's answer that uses 'interact' to work today (later updated in early 2023 is below); however, the ipywidgets documentation presently includes a matplotlib example, which uses 'interactive', that I was able to take and adapt #qqueezz's solution to get it working. This seems to be a much more streamlined route to make an interactive plot.
#%matplotlib inline # from the example in the documentation. but doesn't seem necessary in current JupyterLab 3.1.11 or the classic notebook available now https://github.com/fomightez/communication_voila
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
def my_sine(x, w, amp, phi):
"""
Return a sine for x with angular frequency w and amplitude amp.
"""
return amp*np.sin(w * (x-phi))
def f( w, amp, phi):
plt.figure(2)
x = np.linspace(0, 2 * np.pi, 300)
plt.plot(x, my_sine(x, w, amp, phi), color='C0')
#plt.ylim(-5, 5)
plt.grid(True) #optional grid
plt.show()
interactive_plot = interactive(f, w=(0, 10, 1), amp=(0, 4, .1), phi=(0, 2*np.pi+0.01, 0.01))
#output = interactive_plot.children[-1]
#output.layout.height = '450px'
interactive_plot
You can go to the repo here, launch a session by choosing the launch binder badge to the right of 'Start with the matplotlib & widget demo as a notebook' under 'Direct links to start out in notebook mode:'.
Or click here to launch directly into that notebook via MyBinder.
UPDATE:
Later (early 2023), I found queez's code from Kapernikov: Ipywidgets with matplotlib did work with interact in JupyterLab using ipympl.
Not following yet what changed; however, wanted to note.
import numpy as np
from matplotlib_venn import venn2, venn2_circles, venn2_unweighted
from matplotlib_venn import venn3, venn3_circles
from matplotlib import pyplot as plt
plt.title(print("Shared",Signature_1, 'and',Signature_2, 'and',Signature_3))
venn3(subsets = (len(NameA), len(NameB), len(shared_A_B), len(NameC), len(shared_A_C),
len(shared_C_B), len(shared_A_B_C)), set_labels = (Signature_1, Signature_2, Signature_3), alpha = 0.5)
plt.show()
This code produces titles for plots in jupyter notebook only. When I run the .py script in Anaconda prompt only the plot is visible. How would I go about getting the titles to appear in the plot window? I realized because these are formatted to take variables [plt.title(print("title",variable,etc.)] that they do not work in command line. Any suggestions would be appreciated
You can use the .format method to include a variable into the print/title.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x**2
plt.plot(x,y)
variable ='IamVar'
Signature_1='one'
Signature_2='two'
Signature_3='three'
# \n stands for newline
plt.suptitle("Moving title - {} and {},{} \n set=({},{})".format(Signature_1,Signature_2,Signature_3,len(x),len(y))
,size=8,x=0.3, y=0.6)
plt.show()
I have a question regarding creating a chart in Python using matplotlib and then deleting it to create a fresh chart. I find that when I create a chart called 'firstscatter' and then put in a print statement to print it to my Python console in Spyder, it prints the chart which is fine. However I want the chart to be deleted after it has been printed so that I can have a fresh 'secondscatter' chart printed.
So all in all what I want to see is the firstscatter chart printed, then deleted, and then the secondscatter chart printed.
How do I amend my code below to see both charts printed after running the code?
Thanks a lot and really appreciate your help.
import numpy as np
from numpy import random
import pandas as pd
from matplotlib import pyplot as plt
x = random.rand(30)
print (x)
y = random.rand(30)
print (y)
z = random.rand(50)
print (z)
firstscatter = plt.scatter(x,y,s = z * 777)
print (firstscatter)
firstscatter.remove()
secondscatter = plt.scatter(x,y,s = z*777, c='Chartreuse')
print (secondscatter)
When using Matplotlib, you must use plt.show() to show the current figure. In your case:
import numpy as np
from numpy import random
import pandas as pd
from matplotlib import pyplot as plt
x = random.rand(30)
print (x)
y = random.rand(30)
print (y)
z = random.rand(50)
print (z)
plt.scatter(x,y,s = z * 777)
plt.show()
plt.scatter(x,y,s = z*777, c='Chartreuse')
plt.show()
Instead of plt.show(), you can use plt.clf() to clear the current figure.
I am producing a few hundred matplotlib plots, I work in Jupyter Notebook. Each have it's own title. I want to be able to search for these titles. So when I download the file as html, and open it in browser, I'd like to find the title via using ctrl-f. How can I do that?
More details, here is an MCVE:
import matplotlib.pyplot as plt
x=range(5);y=range(5)
for i in range(6):
plt.figure()
plt.plot(x,y)
plt.title("Title"+str(i))
This produces nice plots, titled Title0 Title1 ... Title5. Howevere, these titles are part of the file and not searchable by ctrl-f, or browser doesn't detect them as text, though it would be desired.
I can do it in gnuplot but now I'd like to stick to Python.
You can generate markdown within a Jupyter notebook. Try this:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import display, Markdown
display(Markdown('Title of graph goes here'))
x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o', color='black');
Edit: I've just realised that in your example all the titles will be printed before the graphs. The solution is:
import matplotlib.pyplot as plt
# DO NOT USE %matplotlib inline
x=range(5);y=range(5)
for i in range(6):
ax = plt.figure()
_ = plt.plot(x,y)
title = "Title"+str(i)
display(Markdown(title))
display(ax)
You may print title for every figure (plt.show() necessary in this case):
import matplotlib.pyplot as plt
x=range(5);y=range(5)
for i in range(2):
plt.figure()
plt.plot(x,y)
plt.title("Title"+str(i))
print("Title"+str(i))
plt.show()
Trying to do some plotting in SymPy -
As per this video I have written :
from sympy.plotting import plot, plot_parametric
e = sin(2*sin(x**3))
plot(e, (x, 0, 5));
But after evaling that cell I don't get any output? There isn't an error or
anything, it just doesn't display anything.
Another test :
from sympy import *
from sympy.plotting import plot, plot_parametric
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
expr = x**2 + sqrt(3)*x - Rational(1, 3)
lf = lambdify(x, expr)
fig = plt.figure()
axes = fig.add_subplot(111)
x_vals = np.linspace(-5., 5.)
y_vals = lf(x_vals)
axes.grid()
axes.plot(x_vals, y_vals)
plt.show();
So Im not sure what I'm doing wrong here, I'm not getting any errors though?
If the virtual environment content is of any interest here's a tree of that :
venv
I'm running this on Linux Ubuntu. The virtual environment that it's running in can be seen in the above paste link
You need to use the magic functions, more specifically the ones for matplotlib:
%matplotlib qt # displays a pop-up of the plot
%matplotlib inline # keeps it within the notebook
Runnable example using Python 3.4 Nov '15:
from sympy import *
from sympy.plotting import plot, plot_parametric
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
expr = x**2 + sqrt(3)*x - Rational(1, 3)
lf = lambdify(x, expr)
fig = plt.figure()
axes = fig.add_subplot(111)
x_vals = np.linspace(-5., 5.)
y_vals = lf(x_vals)
axes.grid()
axes.plot(x_vals, y_vals)
To get plots to show inline in the IPython notebook, you need to enable matplotlib's inline backend. You can do this by running
%matplotlib inline