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
Related
I'm studying about Fourier Series with python.
I drew it with cosine and sine function.
My code is like this.
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
x = Symbol('x')
fx=0
j=10
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
plt.plot(x_val,y_val)
plt.show()
I could get the correct graph.
And I tried to make the graph into animaion effect like this gif file.
enter image description here
I wrote the code like below using by ArtistAnimation , but I couldn't get the animation.
How can i get the animation?
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from matplotlib.animation import ArtistAnimation
x = Symbol('x')
fx=0
j=10
img=[]
fig, ax=plt.subplots(constrained_layout=True)
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
fs=plt.plot(x_val,y_val)
img.append([fs])
anim=ArtistAnimation(fig,img,interval=5)
anim.save("Fourier_Series01.gif",fps=24)
I tried to make the code with ArtistAnimation
Thank you for your answer
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 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()
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.
I created the following test code, and the code runs fine. But the plot does not appear when executed. Did I miss something? I use pyplot to create the plots. When I use plt.savefig("test.png") the chart is created and saved.
import numpy
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from studentRegression import studentReg
from class_vis import prettyPicture, output_image
from ages_net_worth import ageNetWorthData
ages_train, ages_test, net_worths_train, net_worth_test = ageNetWorthData()
plt.clf()
plt.scatter(ages_train, net_worths_train, color="b", label="train data")
plt.legend(loc=2)
plt.xlabel("ages")
plt.ylabel("net worths")
plt.show()
def ageNetWorthData():
random.seed(42)
numpy.random.seed(42)
ages = []
for ii in range(100):
ages.append( random.randint(20,65) )
net_worths = [ii * 6.25 + numpy.random.normal(scale=40.) for ii in ages]
### need massage list into a 2d numpy array to get it to work in LinearRegression
ages = numpy.reshape( numpy.array(ages), (len(ages), 1))
net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1))
from sklearn.cross_validation import train_test_split
ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths)
return ages_train, ages_test, net_worths_train, net_worths_test
You are using a "non-interactive" backend (agg). Just remove the line:
matplotlib.use('agg')
You can check the docs here.