ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 16 Jun 2024 18:23:19 +0200How to add arrow tips to axeshttps://ask.sagemath.org/question/77699/how-to-add-arrow-tips-to-axes/I would like to have the axes displayed with arrow tips at the end. I have seen this question asked before but since that was some time ago I wondered if there is a simple way to do it now that doesn't involve plotting them manually. I appreciate the help.Graph KarlThu, 30 May 2024 17:00:26 +0200https://ask.sagemath.org/question/77699/Plot real to complex functionhttps://ask.sagemath.org/question/77872/plot-real-to-complex-function/I have a function that has real domain and a complex co-domain. I want to plot the real and imaginary parts together, like this: imgur.com/a/yb7g5Ce
The code that I used to generate that plot (`plot(real(F(x)),(-2,2)) + plot(imag(F(x)),(-2,2),color="red")`) works, but I think every value is being calculated two times, discarding either the real or the imaginary part. Is there any way to get this effect more efficiently, without doing useless calculations?ThePirate42Sun, 16 Jun 2024 18:23:19 +0200https://ask.sagemath.org/question/77872/plotting origin locationhttps://ask.sagemath.org/question/75652/plotting-origin-location/plotting some basic functions in sage, quadratic, abs value, etc. Then setting four up in an array. Problem; the square root function plots, but the frame and axes adjust so only the defined values show on the axes, and the origin and y axis are moved to the far left of the frame, not in the center, the image below will show the problem. Cannot find a way to remedy this, and plot the square root so the axes and frame stay put, i.e. centered, like the other three functions plot.
Here is the code;
p1 = plot(-sqrt(-x-2)+1, (x,-10,8),xmin=-10,xmax=10,ymin=-10,ymax=10,gridlines="minor",frame=True,axes=True,figsize=(3,3),thickness='3') # the function ,followed by the domain
p2 = plot(-abs(x+2)-3, (x,-10,10),xmin=-10,xmax=10,ymin=-10,ymax=10,gridlines="minor",frame=True,figsize=(3,3),thickness='3')
p3= plot(-(x-4)^3+1, (x,-10,10),xmin=-10,xmax=10,ymin=-10,ymax=10,gridlines="minor",frame=True,figsize=(3,3),thickness='3') # the function ,followed by the domain
p4= plot(-.5*(x-4)^2+1, (x,-10,10),xmin=-10,xmax=10,ymin=-10,ymax=10,gridlines="minor",frame=True,figsize=(3,3),thickness='3') # the function ,followed by the domain
combined=myplot+myplot2
(myplot).show(title='A',frame=True,figsize=(5,5))
graphics_array(((p1,p2), (p3,p4))) # long time
Graphics Array of size 2 x 2
Here is the output; (Sorry, new user, cannot upload a file)metanosisThu, 25 Jan 2024 12:19:43 +0100https://ask.sagemath.org/question/75652/Can we control the size of a plot, so I can use apng() in animationhttps://ask.sagemath.org/question/75497/can-we-control-the-size-of-a-plot-so-i-can-use-apng-in-animation/I know how to control the size of a plot when I show the plot, eg: `g.show(figsize=[3,5])`
The following Sagemath code works without installing ImageMagick or FFmpeg, it is quite convenient.
<pre>
frames = [plot(cos(k*x), (-pi, pi)) for k in range(1,7)]
a = animate(frames)
a.apng(savefile='ex1.png', show_path=True)
</pre>
Unfortunately, the following will produce error:
<pre>
frames = [plot(cos(x^k), (-2, 2)) for k in range(1,7)]
a = animate(frames)
a.apng(savefile='ex2.png', show_path=True)
</pre>
After I done some debugging, I found that the individual frames produced in the for loop all have the same size.
The he individual frames produced in the for loop do not all have the same size. I played with the apng() more and find that apng() seems to expect all frames to have the same size.
How can we control the plot so that the image produced in the memory all have the same size. I am not concerning with the 'display size on the screen', I am concerning with the 'size as seen by the apng() in the memory' in the for loop.
I would like to have the following option to force all frames resize to the same size when putting all frames together.
`animate(frames, figsize=[3,5])`. or `apng(frames, figsize=[3,5])`
mlvTue, 16 Jan 2024 17:01:00 +0100https://ask.sagemath.org/question/75497/Plotting transition-of-transition fails with "cannot evaluate symbolic expression"https://ask.sagemath.org/question/74729/plotting-transition-of-transition-fails-with-cannot-evaluate-symbolic-expression/Hi Manifolds experts, and many thanks in advance for any help.
I am trying to do a simple exercise (as I thought) to understand how SageMath Manifolds "composes" transitions between maps. Actually, I was very impressed this can be done.
To do this myself, I define the usual cartesian coordinates `X` and spherical coordinates `Y`. In addition, define spherical orthonormal coordinates `H`.
Here is my code to set it all up:
from sage.all import *
from IPython.display import display, Math, Latex
%display latex
M = Manifold(4, 'M', latex_name=r'\mathcal{M}', structure='Lorentzian')
X.<t,x,y,z> = M.chart()
U = M.open_subset('U', coord_def={X: (y!=0, x<0)})
X_U = X.restrict(U)
display(Latex(f'$X_U = {latex(X_U)}$'))
Y.<t,r,th,ph> = U.chart(r't:(-oo,+oo) r:(0,+oo) th:(0,+pi):\theta ph:(0,2*pi):\phi')
transit_Y_to_X = Y.transition_map(X, [
t, r*sin(th)*cos(ph), r*sin(th)*sin(ph), r*cos(th)
])
transit_Y_to_X.set_inverse(
t, sqrt(x^2+y^2+z^2), arccos(z/sqrt(x^2+y^2+z^2)), atan2(y,x)
)
H.<t,r,th_,ph_> = U.chart(r't:(-oo,+oo) r:(0,+oo) th_:(0,+oo):\hat{θ} ph_:(0,+oo):\hat{φ}')
transit_H_to_Y = H.transition_map(Y, [
t, r, th_/r, ph_/(r*sin(th))
])
display(transit_H_to_Y)
display(transit_H_to_Y.display())
transit_H_to_Y.inverse().display()
Then, I introduce the composed transition (the point of my exercise):
transit_H_to_X = transit_Y_to_X * transit_H_to_Y
display(transit_H_to_X)
display(transit_H_to_X.display())
transit_H_to_X.set_inverse(
t,
sqrt(x^2+y^2+z^2),
r*arccos(z/sqrt(x^2+y^2+z^2)),
r*sin(th)*atan2(y,x)
)
transit_X_to_H = transit_H_to_X.inverse()
display(transit_X_to_H)
display(transit_X_to_H.display())
and try to plot H against X:
H.plot(chart=X,
ambient_coords=(x,y,z), fixed_coords={t:0},
ranges={r:(1,1.1), th_:(1.1,1.2)}, number_values=3,
)
This fails with errors `TypeError: cannot evaluate symbolic expression numerically`. Any ideas on how I can make this work, please? What am I doing wrong?
I am using SageMath 9.5 on Ubuntu 22.04.
Thanks
GPN
GPNThu, 07 Dec 2023 17:09:50 +0100https://ask.sagemath.org/question/74729/Plot a planar graph as a plane graphhttps://ask.sagemath.org/question/74735/plot-a-planar-graph-as-a-plane-graph/ I have a graph D which is the bipartite graph of a matrix Y. I know this graph is planar, however when I plot it using the .plot() and output it using .save() it does not plot as a plane graph. I was wondering if there was any nice way to output a graph in a planar form (namely, such that none of the edges intersect). According to this website on the plotting sage math website (can't post url since my karma is too low) there is a plot option 'layout' which seems to have the option 'planar'. I am unsure how to test this, or if this would even achieve what I'm interested in doing. wizard7703Thu, 07 Dec 2023 21:15:09 +0100https://ask.sagemath.org/question/74735/How to plot the real line in SageMathhttps://ask.sagemath.org/question/73437/how-to-plot-the-real-line-in-sagemath/I am preparing a SageMath Jupyter notebook for expository purposes. I would like to be able to display the real line, with chosen points on it, and some arrows between certain pairs of points.
While this would be easy to do in LaTeX (by means of TikZ), I do not know how to do it in Sage. This feels like something that should be well within Sage's capabilities. What to do?
Let me give an easy, concrete example. Say I want to plot the points -5/11 + \beta, -4/11 + \beta,..., 5/11+\beta (labelled as such) on the real line, where $\beta = 1/50$ (for instance).
In a second version of the graph, I also want curved arrows going from -5/11+\beta to -4/11+\beta, from -4/11+\beta to -3/11+\beta, and so on until -2/11+\beta to -1+\beta; I also want a curved arrow from -1+\beta to 0.
How to do this?
Update: Let me include some (extremely amateurish) TikZ code, so that people can see exactly what I want:
\begin{tikzpicture}
\def\scale{2}
\def\bet{0.2}
\draw[-] (-\scale*3.5,0) -- (\scale*3.5,0);
\foreach \i in {-3,...,3} {
\draw[shift={(\scale*\i,0)},color=gray] (0pt,0pt) -- (0pt,-3pt) node[below] {$\frac{\i}{q}$};
\filldraw (\scale*\i+\scale*\bet,0) circle (2pt) node[above] {$\frac{\i}{q}+\beta$};
}
\foreach \i in {-3,...,-2} {
\draw[*->*] (\scale*\i+\scale*\bet-0.08,0.04) to[bend right] (\scale*\i+\scale*\bet+\scale+0.08,0.04);
}
\draw[*->] (-\scale+\scale*\bet-0.08,0.04) to[bend right] (0,0);
\end{tikzpicture}
I'd gladly include the result here, but I do not yet have enough points to upload files :(.
Of course I can just include the resulting image in my Jupyter notebook, but for some reason Jupyter is refusing to display vector graphics, and will display the image only if it is very low-resolution. Wouldn't it be nice if there were a way to do this within Sage...GaraldSun, 17 Sep 2023 14:01:01 +0200https://ask.sagemath.org/question/73437/graph plot: size of arrow headshttps://ask.sagemath.org/question/69770/graph-plot-size-of-arrow-heads/Hi !
I was wondering how I could reduce the size of arrow heads while plotting a directed graph. I haven't got enough "points" to upload a picture, but you can easily understand what happens : I have a directed graph with many vertices, I use vertex_size= something small, but the arrow heads are very very large and the whole thing looks weird.
any idea?
thanks!pg261Thu, 06 Jul 2023 16:24:05 +0200https://ask.sagemath.org/question/69770/plot with varying color linehttps://ask.sagemath.org/question/72679/plot-with-varying-color-line/Is there a way to plot a complex function of a single real variable
so that the color of the line represents the argument of the
complex function and the vertical position of the line represents
the norm of the complex function.
For example can this be modified so that the color of the line
represents the argument of the function?
f(x) = exp(5*i*x) * exp(-x^2/20) # complex gaussian wave packet
plot(abs(f(x)), x, -10,10) # plot magnitude of the function
Is there anything available along the lines of this:
plot(abs(f(x), x, -10, 10, linecolor = hue(complex_to_hue(f(x))))takashiFri, 18 Aug 2023 06:46:17 +0200https://ask.sagemath.org/question/72679/How to color area between 2+ functionshttps://ask.sagemath.org/question/70807/how-to-color-area-between-2-functions/
y1 =(4-x)/2
y2 = 2 - 2*x
y3 = (-3+x)/2
plot([y1,y2,y3], (x,-1,6), ymax=10, ymin=-4,gridlines='minor')
I want to colorize the triangle formed by these 3 linear functions. How can I do that? fill = True just confuses the graph.Alex89Mon, 24 Jul 2023 10:17:13 +0200https://ask.sagemath.org/question/70807/Mysterious Disappearance of an edgehttps://ask.sagemath.org/question/69703/mysterious-disappearance-of-an-edge/Software version: **Sage 10.0**
The following codes can find all connected subgraphs.
g = graphs.CubeGraph(2)
subgraphs = list(g.connected_subgraph_iterator())
G=graphics_array([[v.plot() for v in subgraphs]],3,5)
G.show(axes=False, frame=False, figsize=5)
We will notice that there is an image missing an edge (due to the non-unique nature of iteration order, in my execution, it is the 6th one, and its image should be one edge instead of two isolated vertices).
![image description](/upfiles/16884710505555375.png)
The previous images might appear confusing because they are not separated by borders. I'm not know how to **uniformly add nice borders** to them (**which is also the question I've been wanting to ask**), otherwise, it would make the above issue more clear. The following images have been processed by using Inkscape. We can clearly see that the 6th image is missing an edge.
subgraphs[5].edges(sort=true,labels=False) # output: [('00', '01')]
![image description](/upfiles/16884717102411836.png)lichengTue, 04 Jul 2023 14:03:04 +0200https://ask.sagemath.org/question/69703/SageTex - Initializing plots directory fails in external drive.https://ask.sagemath.org/question/69631/sagetex-initializing-plots-directory-fails-in-external-drive/Hello,
MacOS 13.4.1 - TexLive 2023 - SageMath version 10.0, Release Date: 2023-05-20 │
│ Using Python 3.11.1.
When I run
% !TEX TS-program = sage
\documentclass{article}
\usepackage{sagetex}
\begin{document}
\begin{sagesilent}
G = plot(sin(x),-pi,pi)
\end{sagesilent}
This is
\sageplot{G}
my plot
\end{document}
I have 3 different results for these two cases:
a) Whether the sage-plots-for-Untitled.tex directory exists or not.
b) whether the location is an external device or not.
If the directory does not exist (running for the first time or has been deleted), the result is as expected for both cases, where the files are on the internal or external hard drive.
If the directory already exists, the result is as expected if the files are on the internal hard drive.
If the files are on an external drive and the directory exists, sagetex fails with:
Processing Sage code for Untitled.tex...
Code block (line 7) begin...end
Initializing plots directory
**** Error in Sage code on line 12 of Untitled.tex! Traceback follows.
Traceback (most recent call last):
File "/Volumes/TOSHIBA4T/teste/Untitled.sagetex.sage.py", line 19, in <module>
_st_.plot(_sage_const_0 , format='notprovided', _p_=G)
File "/private/var/tmp/sage-10.0-current/local/var/lib/sage/venv-python3.11.1/lib/python3.11/site-packages/sagetex.py", line 225, in plot
self.initplot()
File "/private/var/tmp/sage-10.0-current/local/var/lib/sage/venv-python3.11.1/lib/python3.11/site-packages/sagetex.py", line 107, in initplot
shutil.rmtree(self.plotdir)
File "/private/var/tmp/sage-10.0-current/local/var/lib/sage/venv-python3.11.1/lib/python3.11/shutil.py", line 732, in rmtree
_rmtree_safe_fd(fd, path, onerror)
File "/private/var/tmp/sage-10.0-current/local/var/lib/sage/venv-python3.11.1/lib/python3.11/shutil.py", line 683, in _rmtree_safe_fd
onerror(os.unlink, fullname, sys.exc_info())
File "/private/var/tmp/sage-10.0-current/local/var/lib/sage/venv-python3.11.1/lib/python3.11/shutil.py", line 681, in _rmtree_safe_fd
os.unlink(entry.name, dir_fd=topfd)
FileNotFoundError: [Errno 2] No such file or directory: '._plot-0.pdf'
**** Running Sage on Untitled.sage failed! Fix Untitled.tex and try again.
Anyone else had these problem? Can you help me? Is this a VenturaOS Privacy & Security issue?
Thanks,
FilipeqgfreireFri, 30 Jun 2023 20:03:36 +0200https://ask.sagemath.org/question/69631/Aspect_ratio of a diskhttps://ask.sagemath.org/question/68235/aspect_ratio-of-a-disk/ A nice graphics to the point of the deformation of the disk
var('x y u B')
assume(x>=0)
assume(y>=0)
assume(α>=0)
assume(α<=1)
assume(β>=0)
assume(β<=1)
assume(u>1)
U(x,y) = x^.5*y^.5
Dep(x,y) = .75*x +.25* y
sol0=solve(U(x,y)==u,y)
sol1=solve(Dep(x,y)==B,y)
Incd(x,u)=sol0[0].rhs()#définition d'une courbe d'indifférence
#Même chose pour la droite de budget
Bud(x,B)=sol1[0].rhs()
sol2=solve(Bud(x,B)==0,x)
x0(B)=sol2[0].rhs()
B=0.85
p=plot(Incd(x,.5),(x,0.0575,x0(B)+.25),axes=False,linestyle='--')
p+=plot(Incd(x,.65),(x,0.1,x0(B)+.25),axes=False,linestyle='--')
p+=plot(Incd(x,1.2),(x,0.3,x0(B)+.25),axes=False,linestyle='--')
p+=plot(Incd(x,1.3),(x,0.35,x0(B)+.25),axes=False,linestyle='--')
p+=plot(Bud(x,B),(x,0,x0(B)),axes=False,thickness=2,color='green')
p+=arrow((0,0),(0,Bud(0,x0(B)+.15)),color='black')
p+=arrow((0,0),(x0(B)+0.5,0),color='black')
p+=text(r'$y$',(-.05,Bud(0,x0(B)+.15)),color='black',fontsize=14)
p+=text(r'$x$',(x0(B)+0.55,0),color='black',fontsize=14)
p+=text(r'$0$',(-.05,-.05),color='black',fontsize=14)
p+=text(r'$\frac{R}{p_x}$',(x0(B),-.25),color='black',fontsize=14)
p+=text(r'$\frac{R}{p_y}$',(-.05,Bud(0,B)),color='black',fontsize=14)
p+=text(r'$R=xp_x+yp_y}$',(.5,2.1),color='black',rotation=-41,fontsize=14)
p+=text(r'$\alpha$',(1.,.135),color='black',fontsize=14)
p+=text(r'''$\frac{p_x}{p_y}=\frac{R/p_x}{R/p_y}= \tan(\alpha)}$''',(2,2),color='black',fontsize=14)
p+=text(r'$U_1$',(1.45,.125),color='black',fontsize=10)
p+=text(r'$U_2$',(1.45,.3),color='black',fontsize=10)
p+=text(r'$U_n$',(1.475,1.025),color='black',fontsize=10)
p+=text(r'$U_{n+1}$',(1.475,1.2),color='black',fontsize=10)
#p+=arc((x0(B), 0), .15,.45, sector=(RDF.pi()/1.65, RDF.pi()),color='red',=True)
p+=disk((x0(B),0.0), .3, (1.2*pi/2, pi), color='lightgrey',aspect_ratio=1)
show(p,aspect_ratio=1/3)
I understand that he`show(p,aspect_ratio=1/3)` comming after the aspect ratio of the disk, takes all. What can I do ?
CyrilleSun, 07 May 2023 11:24:52 +0200https://ask.sagemath.org/question/68235/Parametric_plot gives half-broken picture for transcendental functionhttps://ask.sagemath.org/question/68147/parametric_plot-gives-half-broken-picture-for-transcendental-function/- Goal: Solve 2 functions about Ma1, delta, beta, sigma, and give a contour plot using Ma1 & sigma as axes. (an Aerodynamic problem)
- Problem: One of them is transcendental. I tried:
1. For every give delta & Ma1, create a loop to iterate beta, and numerically solve sigma for every point. But find_root gives Runtime Error, and interrupted the script.
2. Solve the equations for Ma1 & sigma under given delta, and use parametric_plot to give the picture by iterating beta. This works half. The other half of these lines are missed.
3. Substitute delta and use implicit_plot. This works on plotting eq1 using Ma1 & beta as axes. But I have no idea of introducing 3 variables in order to give a 2D plot.
I think it's not a numerically unsolvable problem since my classmates got a picture using MATLAB. But I couldn't figure out what's wrong with sagemath. Maybe it's because of the order of solving equations? Or, maybe it's the limit of sagemath?
Please give me a little help, thanks.
Script of attempt 2:
from sage.plot.colors import rainbow
clr=rainbow(8);
#Shock Wave 4
delta,Ma1,Ma2,gamma,beta,pp,sigma=SR.var('delta Ma1 Ma2 gamma beta pp sigma')
eq1=tan(delta)==(Ma1^2*sin(beta)^2-1)/(tan(beta)*(Ma1^2*((gamma+1)/2-sin(beta)^2)+1))
eq1=eq1.subs(gamma=1.4)
eq4=sigma==(2*gamma/(gamma+1)*Ma1^2*sin(beta)^2-(gamma-1)/(gamma+1))^(-1/(gamma-1))*((gamma+1)*Ma1^2*sin(beta)^2/((gamma-1)*Ma1^2*sin(beta)^2+2))^(gamma/(gamma-1))
eq4=eq4.subs(gamma=1.4)
sol4=solve([eq1,eq4],[Ma1,sigma],solution_dict=True)
sud=0;bb=0.05
fg4=parametric_plot((sol4[1][Ma1].subs(delta=sud),sol4[1][sigma].subs(delta=sud)),(beta,0.1,pi/4-bb),color=clr[0],
axes_labels=(r'$Ma_1$',r'$\sigma$'),title=r'$\sigma\ vs\ Ma_1$')
fg4+=text(r'$\delta=0^\circ$',(1.1,0.9),color=clr[0])
for i in range(1,8):
sud=i*pi/36
fg4+=parametric_plot((sol4[1][Ma1].subs(delta=sud),sol4[1][sigma].subs(delta=sud)),(beta,0.1,pi/4-bb),color=clr[i])
fg4+=parametric_plot((sol4[0][Ma1].subs(delta=sud),sol4[0][sigma].subs(delta=sud)),(beta,0.1,pi/4-bb),color=clr[i])
tx=sol4[1][Ma1].subs(delta=sud,beta=pi/2.4)+0.05;
ty=sol4[1][sigma].subs(delta=sud,beta=pi/2.4)+0.02;
delt='$'+str(i*5)+'^\\circ$'
fg4+=text(r'%s'%delt,(tx,ty),color=clr[i])
end
fg4.show(xmin=1,xmax=4,ymin=0,ymax=1,aspect_ratio=2)kaidWed, 03 May 2023 16:28:08 +0200https://ask.sagemath.org/question/68147/Reducing the width of an arrowhttps://ask.sagemath.org/question/67755/reducing-the-width-of-an-arrow/ In the following code I can increase the width of the arrows but not decrease it. How can I do they are obviously to great
f(x,y) = x^.5*y^.5
# Contours from z1 to z2.
# This interval is divided into ni subintervals
z1, z2 = 0, 2
ni = 20
dz = (z2-z1)/ni
levels = [z1,z1+dz..z2]
pl = contour_plot(f(x,y), (x,0,2), (y,0,2), contours=levels,
cmap="gist_yarg", colorbar=false,frame=false,axes=false)
pl += arrow((0,0), (2.1,0),color='black')
pl += arrow((0,0), (0,2.1),color='black')
pl += contour_plot(f, (0,2), (0,2), contours=levels, fill=False)
pl += arrow((0,0), (0,2.1),color='black',width=1,arrowsize=.5) #<- here
pl += text(r'$\overline{U}$', (2.1,0.95),color='red')
pl += text(r'$\overline{\overline{U}}$', (2.1,1.1),color='red')
pl += text(r'''$\mathrm{Courbes\,\, d'indifférence}$''', (1,2.3),color='red')
pl += text(r'''$\mathrm{Fonction\,\, de \,\,Cobb-Douglas\,\, : \,\,} U(x,y) = x^{1/2} y^{1/2}$''', (1,2.2),color='red')
show(pl,axes_labels=['$x$', '$y$'],ticks=[None, None],frame=false)
ThanksCyrilleFri, 21 Apr 2023 16:29:26 +0200https://ask.sagemath.org/question/67755/Some questions on plothttps://ask.sagemath.org/question/67029/some-questions-on-plot/This is a multi-form question. After this question `https://ask.sagemath.org/question/67023/error-in-listing-a-zip/` my code works anew. Do not ask me why ?
But I encounter some new problems. I have had problem to make docker works properly on my computer. But now I would like to enlight the following code (look at 3) for the docker problem)
billes=[ZZ.random_element(0, 4) for i in range(50)]
billes+=[ZZ.random_element(5, 10) for i in range(80)]
billes+=[ZZ.random_element(10, 25) for i in range(21)]
billes+=[ZZ.random_element(25, 50) for i in range(28)]
billes+=[ZZ.random_element(50, 100) for i in range(28)]
shuffle(billes)#no necessary here only to confirm
billes1=sorted(billes)
binbilles1=[[x for x in billes1 if 0 <= x < 4],[x for x in billes1 if 5 <= x < 10],[x for x in billes1 if 10 <= x < 25],[x for x in billes1 if 25 <= x < 50],[x for x in billes1 if 50 <= x < 100]]
avbinbilles1=[len(x)^(-1)*sum(x) for x in binbilles1]
number=[len(x) for x in binbilles1]
cumsumpop=[sum(number[:i]) for i in range(1, len(number)+1)]
percumsumpop=[0]+[sum(number[:i])/sum(number) for i in range(1, len(number)+1)]
cumsumavbinbilles1=[sum(avbinbilles1[:i]) for i in range(1, len(avbinbilles1)+1)]
percumsumavbinbilles1=[0]+[sum(avbinbilles1[:i])/sum(avbinbilles1) for i in range(1, len(avbinbilles1)+1)]
#percumbilles1=[0]+[sum(binbilles1[:i])/sum(number) for i in range(1, len(binbilles1)+1)]
show(percumsumpop)
show(percumsumavbinbilles1)
A=zip(percumsumpop,percumsumavbinbilles1)
p=line([(0,1),(1,1),(1,0)],color='black')
p+=list_plot(list(A),color='red',plotjoined=true,aspect_ratio=1)
p+=line([(0,0),(1,1)])
p+=text(r"$Courbe\,\, de\,\, Lorenz$",(0.2,0.95), color='green')
p+=text(r"$Pourcentages\,\, Cumulés\,\, de \,\, la \,\, Population$",(-0.1,0.5), color='green', rotation=90)
p+=text(r"$Pourcentages\,\, Cumulés\,\, de \,\, la \,\, richesse$",(0.5,-0.1), color='green', rotation=0)
show(p)
1. I would like to fill the space between the red and the blue line but I do not find how
2. I would like to change the font of the ticks and label if I use them but I do not find how
3. I use Docker but I do not know how to gives access to Latex (We need a container with bot Sagemath and latex)
4. Incidently, I do notknow how to make docker remanent. Each time I shut down my computer , I loose all my notebooksCyrilleThu, 23 Mar 2023 00:10:44 +0100https://ask.sagemath.org/question/67029/TypeError: 'sage.rings.integer.Integer' object is not subscriptablehttps://ask.sagemath.org/question/66969/typeerror-sageringsintegerinteger-object-is-not-subscriptable/ def undamped(x, t):
return [x[1], x[0]-x[0]^3]
from scipy.integrate import odeint
from scipy import linspace
coordinates=0
nbpts = 1000 # number of points
endtime = 20 # end of time span
tspan = linspace(0.0, endtime, nbpts)
ics1 = [0.09, 0.0] # first initial conditions
sol1 = odeint(undamped, ics1, tspan)
solx1 = [(tspan[k], sol[m]) for k in range(nbpts)]
xplot1 = list_plot(sol, axes_labels=['t','x'], size=1)
coordinates1 = [(s[0], s[1]) for s in sol1]
phaseportrait1 = list_plot(coordinates,axes_labels=['x','y'], size=1)
a = graphics_array([xplot1, phaseportrait1])
a.show()Adwait1602Fri, 17 Mar 2023 12:05:03 +0100https://ask.sagemath.org/question/66969/plotting ill-conditionned functionhttps://ask.sagemath.org/question/64934/plotting-ill-conditionned-function/ Inspiration [here](https://ask.sagemath.org/question/64794/inconsistentincorrect-value-of-li,mit-involving-tan-and-tanh/).
Let $f(x)\\,=\\,\displaystyle{\frac{d}{dx}\\,\log\left(\tan\left(\frac{1}{2} \\, \pi \tanh\left(x\right)\right)\right)}$.
sage: f
x |--> -1/2*pi*(tan(1/2*pi*tanh(x))^2 + 1)*(tanh(x)^2 - 1)/tan(1/2*pi*tanh(x))
The inspiring question showed that $\lim_{x\rightarrow\infty}=2$. However, computing values of this function for "moderately large" $x$ values is problematic :
sage: [[u, f(u).n()] for u in (5, 10..30)]
[[5, 1.99990923138165],
[10, 1.99999996314183],
[15, 1.99985733718347],
[20, -0.000000000000000],
[25, -0.000000000000000],
[30, -0.000000000000000]]
Trying to plot this illustrates a problem with computing these values
sage: plot(f, (1, 30))
Launched png viewer for Graphics object consisting of 1 graphics primitive
![image description](/upfiles/16688939771208742.png)
The computation is numerically unstable for n>15. One possible workaround is to force a large numerical precision:
sage: [[u, RR(f(u).n(digits=30))] for u in (5, 10..30)]
[[5, 1.99990923138260],
[10, 1.99999999587769],
[15, 1.99999999999981],
[20, 1.99999999999999],
[25, 1.99999999944971],
[30, 1.99999483984586]]
However, this forcing *does not happen* when `plot`ting the values : the numerical instability is somehow masked but large values are incorrect :
sage: plot(lambda u:RR(N(f(u), digits=30)), (1, 30))
Launched png viewer for Graphics object consisting of 1 graphics primitive
![image description](/upfiles/1668894426499315.png)
This problem seems specific to `plot` : computing manually a list of points works as expected :
sage: L=[u for u in (1,11/10..30)]
sage: LP=list(zip(L, map(lambda u:RR(N(f(u), digits=30)), L)))
sage: line2d(LP, ymin=0)
Launched png viewer for Graphics object consisting of 1 graphics primitive
![image description](/upfiles/16688947466725269.png)
One should note that using other forms of $f(x)$, as worked out in the inspiring question, leads to different numerical instabilities in the same region :
sage: plot(f.trig_reduce().trig_simplify().trig_reduce(), (1, 30))
Launched png viewer for Graphics object consisting of 1 graphics primitive
![image description](/upfiles/166889507712370.png)
I also tried to define a symbolic function, a Python function and a Cython functin doing the same computation with forced precision, to no avail...
Hence the questions:
- Why does `plot` *ignores* the specification of precision ?
- Is there a workaround ?
Bonus questions :
- What is the cause of this numerical instability ?
- can this problem be diagnosed algorithmically (and possibly cured by forcing higher precision in umerically instable region, in a way close to what "detect_poles` do) ?
- is there a better form of $f$ allowing a better numerical approximation in the questionable region ?
Any hint welcome !Emmanuel CharpentierSat, 19 Nov 2022 23:11:19 +0100https://ask.sagemath.org/question/64934/implicit_plot doubled straight linehttps://ask.sagemath.org/question/64916/implicit_plot-doubled-straight-line/ How come this plotted straight line is doubled?
x, y = var('x,y')
show(implicit_plot((y-x-1/2)^2,(x,-5,5),(y,-5,5), color='red'),gridlines=True)
I am looking for the zeros of the polynomial (y-x-1/2)^2. Obviously this has the same zeros as (y-x-1/2). Somehow the plot draws two parallel straight lines.
My attempt to display a plot here failed and I cannot upload any files, yet, due to a lack of points on this forum.Tintin1Sat, 19 Nov 2022 15:02:27 +0100https://ask.sagemath.org/question/64916/Why is a png viewer not loading?https://ask.sagemath.org/question/63924/why-is-a-png-viewer-not-loading/Question 54175 is the same issue highlighted previously without solution.
This is so frustrating as it's the first time I'm using Sage
and the whole process has been incredibly annoying
to set up and I can't even view my plot!
I'm using SageMath 9.6, using Ubuntu on Windows.
Here's my code:
sage: vector_field(X, Y) = (0.9*X - 0.5*Y, 0.1*X + 0.8*Y)
sage: p = plot_vector_field(vector_field,
....: (X, -2, 2), (Y, -2, 2),
....: frame=False,
....: color="green",
....: plot_points=10,
....: axes_labels=("$X$", "$Y$"))
sage: show(p, aspect_ratio=1, figsize=5)
Launched png viewer for Graphics object consisting of 1 graphics primitive
But no png viewer is launched!OpenSauceCoolTue, 06 Sep 2022 14:19:01 +0200https://ask.sagemath.org/question/63924/compose (non-)symbolic functionshttps://ask.sagemath.org/question/63574/compose-non-symbolic-functions/I wonder how to compose with a non-symbolic function, or, more generally, how to compose several functions, if some of them are non-symbolic.
In my concrete case, I wish to plot a transformed Gaussian distribution function (concretely, the Camp-Paulson approximation), comparing with a plot of probabilities of the binomial distribution this approximates.
What works, but is not flexible enough is:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
CP=plot(lambda k:T.distribution_function(-1/3*(((0.95*k + 0.95)/(-0.05*k + 1.0))^(1/3)*(1/(k + 1) - 9) + 1/(k - 20) + 9)/sqrt(((0.95*k + 0.95)/(-0.05*k + 1.0))^(2/3)/(k + 1) - 1/(k - 20))),(k,-1,21) , rgbcolor=(0.8,0,0))
show(Bin+CP)
This option has the argument of T.distribution_function hard coded. I rather would have this computed from n and p, using another function. I have two approaches so far, that both don't work.
The first one has a function K computing the input to T.distribution_function like so:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
#
a = 1/(9*n-9*k)
b = 1/(9*k+9)
r = (k+1)*(1-p)/(n*p-k*p)
c = (1-b)*r^(1/3)
μ = 1 - a
σ = sqrt(b*r^(2/3) + a)
def K(k): return (c - μ)/σ
#
CP=plot(lambda k:T.distribution_function(K(k)),(k,-1,21), rgbcolor=(0.8,0,0))
show(Bin+CP)
another alternative tries to set up the composed function before entering plot like so:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
#
a = 1/(9*n-9*k)
b = 1/(9*k+9)
r = (k+1)*(1-p)/(n*p-k*p)
c = (1-b)*r^(1/3)
μ = 1 - a
σ = sqrt(b*r^(2/3) + a)
def distCPapprox(k): return T.distribution_function((c - μ)/σ)
#
CP=plot(lambda k:distCPapprox(k),(k,-1,21), rgbcolor=(0.8,0,0))
show(Bin+CP)
Both approaches don't work. I searched extensively for advice for function composition but couldn't find anything helpful. Your advice is greatly appreciated.oloidSun, 07 Aug 2022 17:36:19 +0200https://ask.sagemath.org/question/63574/Plot drops exponent when scientific notation appears on the y-axishttps://ask.sagemath.org/question/63469/plot-drops-exponent-when-scientific-notation-appears-on-the-y-axis/Just starting out with Sagemath so apologies if this is trivial - I've had a look online and in the forums but not found the answer - though it seems like this should be well-known if it is a problem!
For Sagemath 9.6 both installed on my own machine (an M1 MacBook Pro) and also CoCalc, I'm having the problem that when I plot figures with large scales on the y-axis, often the power is being cut off. For example if I try
plot(x^2,0,150000)
the y-axis is labelled 0, 0.5, 1.0, 1.5, 2.0 - the 10^10 (or e10) is missing. If I decrease the x-range then it sometimes comes back (but sometimes doesn't). Perhaps the top of the figure with the exponent is just being cut off? Is this a known issue? Or is it a Jupyter problem? If I plot with a semilog scale everything is okay. So I'm thinking it is a display problem of some type.
Update: Switching the kernel to 9.1 this error disappears on CoCalc - it adds the exponents to each number on the y-axis (as oppose to just an e10) at the top. But as far as I can tell it happens for 9.2 or later.iboothMon, 01 Aug 2022 20:09:22 +0200https://ask.sagemath.org/question/63469/Color nodes of posethttps://ask.sagemath.org/question/63211/color-nodes-of-poset/I have a poset Q and an element alpha[4] of Q. If I type "alpha[4] in Q", Sage correctly responds "True".
However, when I ask Sage to plot Q with alpha[4] in a special color, I get a KeyError that looks like it can no longer identify alpha[4] as an element of Q. What is going on?
I can't attach screenshots, so here's the error message in text:
Q.plot(element_colors={"blue":[alpha[4]]})
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-27-a224aeb4e328> in <module>
----> 1 Q.plot(element_colors={"blue":[alpha[Integer(4)]]})
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/combinat/posets/posets.py in plot(self, label_elements, element_labels, layout, cover_labels, **kwds)
2061 cover_labels = False
2062
-> 2063 return graph.plot(vertex_labels=label_elements,
2064 edge_labels=cover_labels,
2065 layout=layout,
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/misc/decorators.py in wrapper(*args, **kwds)
489 options['__original_opts'] = kwds
490 options.update(kwds)
--> 491 return func(*args, **options)
492
493 #Add the options specified by @options to the signature of the wrapped
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/graphs/generic_graph.py in plot(self, **options)
19991 ['black', 'purple', 'yellow', 'yellow']
19992 """
> 19993 return self.graphplot(**options).plot()
19994
19995 def show(self, method="matplotlib", **kwds):
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/graphs/generic_graph.py in graphplot(self, **options)
19639 """
19640 from sage.graphs.graph_plot import GraphPlot
> 19641 return GraphPlot(graph=self, options=options)
19642
19643 def _rich_repr_(self, display_manager, **kwds):
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/graphs/graph_plot.py in __init__(self, graph, options)
304
305 self.set_pos()
--> 306 self.set_vertices()
307 self.set_edges()
308
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/graphs/graph_plot.py in set_vertices(self, **vertex_options)
492 colors = []
493 for i in vertex_colors:
--> 494 pos.extend([self._pos[j] for j in vertex_colors[i]])
495 colors.extend([i] * len(vertex_colors[i]))
496
/ext/sage/9.4/local/lib/python3.9/site-packages/sage/graphs/graph_plot.py in <listcomp>(.0)
492 colors = []
493 for i in vertex_colors:
--> 494 pos.extend([self._pos[j] for j in vertex_colors[i]])
495 colors.extend([i] * len(vertex_colors[i]))
496
KeyError: alpha[4]OliverPMon, 11 Jul 2022 19:35:26 +0200https://ask.sagemath.org/question/63211/I can't generate graphs."The kernel appears to have died"https://ask.sagemath.org/question/62218/i-cant-generate-graphsthe-kernel-appears-to-have-died/ I have installed Sage on my Windows 10 machine
SageMath version 9.3, Release Date: 2021-05-09
Using Python 3.7.10.
I tried to plot something simple like
plot(x^2)
I received this message in Jupyter Notebook:
Kernel Restarting.
The kernel appears to have died. It will restart automatically.
And this message SageMath 9.3 Notebook Server
Unhandled SIGSEGV: A segmentation fault occurred.
This probably occurred because a *compiled* module has a bug
in it and is not properly wrapped with sig_on(), sig_off().
Python will now terminate.
------------------------------------------------------------------------
[I 18:19:09.280 NotebookApp] KernelRestarter: restarting kernel (1/5), keep random ports
WARNING:root:kernel 7bc88a4e-b9a1-488d-bbe6-fa359a6758ab restarted
I have the same problem using matplotlib , for example:
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0,1,10)
plt.plot(t,t**2)
plt.show()
jvg21352Sat, 30 Apr 2022 01:37:24 +0200https://ask.sagemath.org/question/62218/plot P1 or P2 is right, but I see a wrong in the figure(P1+P2), how to solve it?https://ask.sagemath.org/question/61716/plot-p1-or-p2-is-right-but-i-see-a-wrong-in-the-figurep1p2-how-to-solve-it/The plots `P1` and `P2` below are correct,
but when I combine them using `P1 + P2`,
there is a break. How to solve it?
sage: t = SR.var('t')
sage: soln1 = lambda t: 196/3 - 196*exp(-3*t/20)/3
sage: P1 = plot(soln1(t), 0, 30, plot_points=1000)
sage: soln2 = lambda t: 1/10470*(102606*e^t + 573835)*e^(-t)
sage: P2 = plot(soln2(t), 30, 50, plot_points=1000)
P1# the figure is right
P2# the figure is also right
P1+P2 # the figure is wrong in the point (t=30)TimeVectorMon, 28 Mar 2022 12:36:59 +0200https://ask.sagemath.org/question/61716/SageMath plot: Axis label only partly in LaTeX style. Why?https://ask.sagemath.org/question/60622/sagemath-plot-axis-label-only-partly-in-latex-style-why/For bigger scripts it makes sense to define functions outside of the interact def function. Here it is the function g(), which is defined before the def function. I'd like to use this function name as argument for both plot() and as argument for setting the label of the y-axis.
- This works fine as plot argument: `plot( g(a,x), ... )`
- For the y-axis I can use g() and get the correct expression, but its shown in bold.
How can I manage to get the italic latex style for this y-axis label?
Remark: The usual way to set the label of the y-axis ( '$a*x^3$' )
works well, but this is by far not as flexible as using ( eval('g()') ), because g can be changed.
Do you have any hint, how `eval('g()')` in `p.axes_labels` can be handled in a way, that the y-axis also has a latex style font?
Here is a working minimal code exmple:
var('a, x')
g(a,x) = a*x^3
@interact
def _(a=slider([-5..5], default=2, label='Param a: ')):
p = plot(g(a,x),(x,-3,3), color='purple')
# p.axes_labels([ '$x$', '$a*x^3$' ])
p.axes_labels([ '$x$', eval('g()') ])beTue, 11 Jan 2022 12:21:15 +0100https://ask.sagemath.org/question/60622/How can I substitute an unknown function in an expression with a known function?https://ask.sagemath.org/question/60468/how-can-i-substitute-an-unknown-function-in-an-expression-with-a-known-function/I have defined an unknown function "p" with command
p=function("p")
Then I deduced another function, which contains "p":
aws(time)=921600*(-1333.33340000000*time + 2000)/(-3.36000004800000e6*p(time) + 3840000)
Now I would like to plot the function aws(time), by subtituting p(time) with a known function, like:
p(time)=time^0.54
I discovered I can't use .subs() as with free variables, so this doesn't work:
aws.subs(p(time)==time^0.54)
Then how can I substitute the known function, to be able to plot aws(time) finally?
KonstantinTue, 28 Dec 2021 03:11:56 +0100https://ask.sagemath.org/question/60468/How can I plot two parametric functions in a common coordinate system?https://ask.sagemath.org/question/60387/how-can-i-plot-two-parametric-functions-in-a-common-coordinate-system/ I can easily use parametric_plot() to plot 1 parametric function at once. For example
parametric_plot((sin(2*t),cos(3*t)),(t,0.0,9),aspect_ratio=1)
plots a nice Lissajous curve.
I also can plot a circle:
parametric_plot((sin(t),cos(t)),(t,0.0,9),aspect_ratio=1)
But how can I plot both of them in a common coordinate system?
I tried:
parametric_plot([(sin(2*t),cos(3*t)),(sin(t),cos(t))],(t,0.0,9),aspect_ratio=1)
Which doesn't work -> Last error message: ''tuple' object is not callable'
I also tried:
pl1=parametric_plot((sin(t),cos(t)),(t,0.0,9),aspect_ratio=1)
pl2=parametric_plot((sin(2*t),cos(3*t)),(t,0.0,9),aspect_ratio=1)
pl1.add_primitive(pl2)
pl1
Error: 'Graphics' object has no attribute 'options'
Then how can I use parametric_plot() to plot two parametric functions at once, in a common coordinate system?
KonstantinWed, 22 Dec 2021 23:45:43 +0100https://ask.sagemath.org/question/60387/Arrows and the end of an axishttps://ask.sagemath.org/question/59946/arrows-and-the-end-of-an-axis/ Hi,
there has been a post about 10 years ago, but unfortunately not a very nice solution. Is it now possible to add an arrow at the right end of an axis?
Kind regards
mpmpThu, 25 Nov 2021 09:16:12 +0100https://ask.sagemath.org/question/59946/Marker color not consistenthttps://ask.sagemath.org/question/59101/marker-color-not-consistent/I have a simple plot with a legend in different colors. The result will be correct or incorrect depending of the order of the graphic elements.
This code gives an incorrect result:
reset()
Plaut = Graphics()
Plaut+=point([1,1/2],color='blue',size=15,legend_label='Sample point', legend_color='blue')
Plaut+=plot(x/2,x,0,2,color='black', thickness=0.2,legend_label='black line', legend_color='black')
Plaut+=plot(-x/2+1,x,0,2,color='red', thickness=0.2,legend_label='red line', legend_color='red')
Plaut.set_legend_options(loc=(1.1,0), markerscale=1)
show(Plaut, title='Color of the marker - 1.')
see ![Marker Color 1](/upfiles/16320897431508949.png)
while this one (the only difference with the first one being the order of the graphic elements) gives a correct result:
reset()
Plaut = Graphics()
Plaut+=plot(x/2,x,0,2,color='black', thickness=0.2,legend_label='black line', legend_color='black')
Plaut+=plot(-x/2+1,x,0,2,color='red', thickness=0.2,legend_label='red line', legend_color='red')
Plaut+=point([1,1/2],color='blue',size=15,legend_label='Sample point', legend_color='blue')
Plaut.set_legend_options(loc=(1.1,0), markerscale=1)
show(Plaut, title='Color of the marker - 2.')
Here, the result is as expected:
![image description](/upfiles/16320900833480936.png)
For this MWE the correction was easy but when I have a lot of elements it is time consuming and somewhat frustrating to manually find the right configuration. I did not find in the manual a rule to follow to directly get the correct result.c05772Mon, 20 Sep 2021 00:31:45 +0200https://ask.sagemath.org/question/59101/