Got very happy when I learned the potential of applying plotly in my use of Python. I use PyCharm, and found out that I could depict numbers, figures, stats, etc using the above option. Yet I am bit confused. First, executing code including 'import plotly.io as pio' and on the following line 'pio.renderers.default = "browser"' it takes ages for the data and graphics to load, but almost only a split second to open the browser. Second, is there an alternative to the "browser"-choice, e.g. a choice that allowed fig.show() directly in the PyCharm console? - for jupyter I think the alternative is "notebook", but that is not PyCharm. If alternatives exist to pio, i.e. that prompt rendering of code execution in the console, I'd be all ears and eyes. Thx, in advance, for any advice.
import plotly.figure_factory as ff
import plotly.graph_objects as go
import numpy as np
import plotly.io as pio
pio.renderers.default = "browser"
## Create first figure
import plotly.io as pio
pio.renderers.default = "browser"
x1,y1 = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
u1 = np.cos(x1)*y1
v1 = np.sin(x1)*y1
fig1 = ff.create_quiver(x1, y1, u1, v1, name='Quiver')
fig1.show()
## Create second figure
import plotly.io as pio
pio.renderers.default = "browser"
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
Y, X = np.meshgrid(x, y)
u = -1 - X**2 + Y
v = 1 + X - Y**2
fig2 = ff.create_streamline(x, y, u, v, arrow_scale=.1, name='Steamline')
fig2.show()
Sometimes results are indeed rendered in a browser, mostly the browser stops loading and an utterly blank, white screen keeps staring at me. That is why I'd kind of fancied a rendering result as performed in matplotlib where graphics is shown in the console directly.
The official answer to your question is that you can use other renderers like “png” or “svg” as provided by Orca. If your figure is too complex, however, you may have trouble with any renderer, depending on your hardware setup.
More info here: https://plot.ly/python/renderers/
Related
Here is the code that I'm using to plot many plots and save them, but it is eating up all of the available RAM and causes the notebook to crash. I tried adding fig.clf(), del fig, gc.collect, and yet nothing seems to work.
I'm able to save only 38 figures around, then session gets crashed on Google Colab, since RAM gets full.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
print(np.__version__) # 1.19.5
print(mpl.__version__) # 3.2.2, also tried with latest 3.4.1
x = np.arange(0, 280, 0.1)
y = np.sin(x)
for k in range(100):
fig, ax = plt.subplots(6, 2, sharex = True)
fig.set_size_inches(37.33, 21)
for i in range(2):
for j in range(6):
ax[j][i].plot(x, y)
fig.savefig(f'figure{k}.png', dpi = 300)
plt.close(fig)
This is related to the inline backend. The memory leak can be avoided by explicitly switching to the agg backend.
cross ref: matplotlib/issues/20067
maybe if you try to save each figure after it is generated, I mean try putting fig. savefig in the for loop.
Edit: after looking for the issue on google, I found that you might need to buy Colab pro.
So I'm trying to add a line of best fit to a graph using the plt.axhline() feature. The code I have currently is below which is working currently but doesn't include the axhline code,
df = pd.DataFrame(pd.read_csv('test5.csv', sep=','))
x = df["IE ratio"]
y = df["109"]
x1 = df["IE ratio"].mean()
plt.axvline(x1, 0, 1, c= 'k')
plt.scatter(x, y, s = 10)
plt.ylabel('Appearance of mutation')
plt.xlabel('IE spectrum')
plt.show()
I've tried to bring in the plt.axhline() feature but can't work out what I need to put in the bracket to get my desired output.
Here's the plot I get with a red line I've drawn on to show what I'm hoping to produce.
Outputted graph
Thanks in advance for any advice or help!
Computing the mean of 109 for a set of cuts of IE ratio and plotting it might get you a bit further but more information would be needed to give you more relevant advice.
import numpy as np
df['109_mean'] = pd.cut(df['IE ratio'], bins=np.arange(4.6,5.6,0.01))
df.plot('IE ratio', '109_mean')
I managed to get it working using old practise notebooks I have. I used the below code.
import matplotlib as plt
from numpy.polynomial import Polynomial
x = df["IE ratio"]
y = df["44"]
xfit = np.linspace(1.3, 4.0, 30)
q = Polynomial.fit(x, y, deg=5)
plt.scatter(x, y, s = 10)
plt.plot(xfit, q(xfit), c='k')
x1 = df["IE ratio"].mean()
plt.axvline(x1, 0, 1, c= 'k')
Thank you for your advice guys and gals :)
I want to plot on the same graph one function (data coming from an array) and the line between (xmin,ymin) to (xmax,ymax) of data
import numpy as np
import matplotlib.pyplot as plt
exo_data = np.loadtxt('./exoplanets.dat')
au2m = 149597870700
day2seconds = 86400
M_Jupiter = 1.898e27
M_Sun = 1.989e30
G = 6.674e11
R=exo_data[:,0]*au2m
T=exo_data[:,1]*day2seconds
Mp=exo_data[:,2]*M_Jupiter
Ms=exo_data[:,3]*M_Sun
Mstar=np.mean(Ms)
C=(mth.pi*4)/G*Mstar
x=R**3
y=T**2
xmin=np.min(R)
ymin=np.min(T)
xmax=np.max(R)
ymax=np.max(T)
plt.plot([xmin,ymin], [xmax,ymax], color='red')
plt.plot(x,y, 'ro', color='blue')
plt.show
plt.close
I have only the first plot in spyder console, not the second one
Expected this :
I'm not sure if it's going to work for you, I suggest you to try the following
plt.plot([xmin,ymin], [xmax,ymax], x, y,'ro', color = 'red')
plt.show
Try to run the script not in the spider console, but in the editor to the left of it. The console processes command by command, therefore, it will process one plot at the time and print it in the same way.
Create a file code.py with your script, and then run it. You can do this with the play button in spyder, or by going to a console and typing python code.py.
Proof are doing everything right. As stated here. This should work:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
And should produce this.
Finally it works... It's my fault. I declared G with e11 and it must be e-11
I just recently started learning Python (Platform: Python 3.7) for my Signal processing and communications class and so far it has been great. However, I'm having issues reproducing the same resolutional quality that's achievable with MatPlotLib and linspace (shown in the code below) when using the SymPy library. I was wondering if there is any way of achieving the same resolution?
I understand that SymPy works off the MatPlotLib library, on the back-end, but is limited in how much it actually uses. I tried adding sampling rates to the time-domain limits in the sym.plot call, like you can do with linspace, but that doesn't work. Is there anyway to call the linspace function prior to plotting, to improve the plot's resolution, or even without using linspace?
Step 1 shows the necessary plots, using MatPlotLib. Step 2 shows the code I'm trying to develop to produce the same results, but the quality of the waveform is nowhere near the same as Step 1.
import sympy as sym
import matplotlib.pyplot as plt
import numpy as np
# Step 1 & Section Identifiers
fc, fm = 10**9,10**6
wc, wm, Ac, Am = 2*np.pi*fc, 2*np.pi*fm, 8, 2
# Carrier Signal Plot
t = np.linspace(0, 5/fc, 500)
ct = Ac*np.cos(wc*t)
plt.xlabel('Time')
plt.ylabel('c(t)')
plt.plot(t,ct)
plt.show()
# Step 2 & Section Identifiers
t = sym.Symbol('t')
fc, fm = 10**7, 10**4
wc, wm = 2*sym.pi*fc, 2*sym.pi*fm
# Carrier Plot
ct = Ac*sym.cos(wc*t)
sym.plot(ct, (t, 0, 5/fc), ylabel = "C(t)")
Edit
I Found that I could turn off adaptive sampling and manually specifying the number of data points, to smooth out the signal. I have added the edited line(s) necessary to show this!
sym.plot(ct, (t, 0, 5/fc), ylabel = "C(t)", adaptive = False, nb_of_points = 500)
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = np.zeros([10,10,3],dtype=np.uint8)
t2 = (2, 0)
t3 = (0, 0)
cv2.line(img,t2,t3,(0,0,255),2,8)
plt.imshow(img)
plt.show()
The output is
I played around with thickness and line type. It doesn't provide a line no matter what!
EDIT:
After suggesting on the comment I tried different values which are not at the edge, (4,5) and (2,5).
With thickness=2
cv2.line(img,t2,t3,(0,0,255),2,8)
With thickness = 0
cv2.line(img,t2,t3,(0,0,255),0,8)
Your code img = np.zeros([10,10,3],dtype=np.uint8) tells me that your image is 10x10 pixels in size. This way you ain't gonna get a decent line to be shown this way as you request in your code example. You are literately zoomed in approximately 6400x or more. t3 lies left of t2 (that's not logic unless.. Arabic-reading method (right-to-left) is applied) So..lets zoom out at least 2-100 times, and put t2 left of t3 and see what happens!
Approach:
Enlarge your image.. lets say your array goes to 100x100 pixels... then your suggested line by cv2.line(img,t2,t3,(0,0,255),2,8) gets zoomed out as well and more into proportion... and t2 & t3 become t2 = (20, 10) & t3 = (40, 10) in other words... it becomes something looking like a rectangle or a line as we all normally expect to see. If you zoom out again and your np array goes to 1000x1000... adjust t2 and t3 coords if needed and then let us know if your problem remains or is solved.
Based on your example I modified it to show what I meant:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = np.zeros([100,100,3],dtype=np.uint8) # imagesize
t2 = (20, 10) # left coordinate of line.
t3 = (40, 10) # right coordinate of line
cv2.line(img,t2,t3,(0,0,255),2,8)
plt.imshow(img)
plt.show()
To do yourself: Relax and read my personal note... and most of all..play with the code to see the change in diagonal line into something you like to see. Enjoy!
Personal note:
Tahlil: breath in.. and out... my friend... nobody is toying with you! We don't do homework but instead help you to improve you your skills, method of questioning, giving insight in the question you ask and help finding solutions. In return we expect from you that you contribute in helping others as well. Toying gets flagged and removed (almost) by default!
As you stated by sgarizvi to answer in answers... I served you an answer and insight how to improve.. can I now get my cookie ... please. Enjoy life and your stay at SO ;-)