I am trying to plot every serial number in Power Bi using Python. I want to do it with a for loop.
I tried this:
x = dataset['mrwSmpVWi']
c = dataset['c']
a = dataset['a']
b = dataset['b']
y = (c / (1 + (a) * np.exp(-b*(x))))
for number in dataset['Seriennummer']
plt.plot(x,y, linewidth = 4)
plt.title("TEST")
plt.xlabel('Wind in m/s')
plt.ylabel('Leistung in kWh')
plt.xlim(0,25)
plt.ylim(0,1900)
plt.show()
Do I need to define number or can I just say plot the graph for every serial number?
This is my Error:
Error Message:
Þŷτĥоň şĉŗιρт έŕгοґ.
Traceback (most recent call last):
File "PythonScriptWrapper.PY", line 33, in <module>
for number in dataset['Seriennummer']:
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2927, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Python27\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Seriennummer'
Your error tells you your dataset has no column called "Seriennummer". Make sure such a column actually exists in your database. See how to debug small programs
Also, you seem to plot the same thing in every plot. Not sure if this is what you want or you simplified it for your [mre], but just something to keep in mind. You usually want different things in each plot, so you'd be calculating x and y inside the loop.
for index, row in dataset.iterrows():
number = row['Seriennumber']
x = row['mrwSmpVWi']
c = row['c']
a = row['a']
b = row['b']
y = (c / (1 + (a) * np.exp(-b*(x))))
plt.plot(x, y, linewidth = 4)
# plt.whatever else...
You can open a new figure using plt.figure().
You can create a new subplot using plt.subplot()
You can save an existing figure using plt.savefig()
You can clear the current figure using plt.clf()
pyplot has hold = True by default, so plotting repeatedly without plt.show() will add more lines to the same plot.
for number in dataset['Seriennummer']:
# plt.whatever...
# REMEMBER, NO PLT.SHOW()
# show the plot AFTER you've plotted everything
plt.show()
So, to overwrite the same figure, but save it to png before creating the new one, you'd do this:
for number in dataset['Seriennummer']:
# plt.whatever...
plt.savefig(f"./plot{number}.png") # Saves as a png
plt.clf() # Clears figure
To create a new figure every time (so you don't need to overwrite the previous one), you'd do this:
for number in dataset['Seriennummer']:
plt.figure()
# plt.whatever...
plt.savefig(f"./plot{number}.png") # Saves as a png
To create a grid of subplots, you'd do this:
nrows = 3
ncols = math.ceil(len(dataset['Seriennummer']) / nrows)
for plotnum, number in enumerate(dataset['Seriennummer']):
plt.subplot(nrows, ncols, plotnum)
# plt.whatever...
# after loop is done, save
plt.savefig(f"./plot_all.png") # Saves as a png
Related
I am trying to plot streamlines in matplotlib over a contour plot by combining these two plots shown below but showing my code first:
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines(lw=1)
clevs = np.linspace(-3., 3., 13)
cnplot = plt.contourf(lon,lat,anomspeed,clevs,add_labels=True,cmap='jet')
cbar = plt.colorbar(cnplot)
cbar.set_label('Standard Deviations')
plt.title('~50m Wind Speed Anomaly {} 2020'.format(calendar.month_name[currm-1]))
diffu = (uwndc - uwnd); diffv = (vwndc - vwnd)
lonn, latt = np.meshgrid(lon, lat)
plt.streamplot(lonn[0,:], latt[:,0], diffu, diffv, density=(3.5,3.5),
color='k',linewidth=0.4,arrowsize=0.6)#x,y 1D and u,v are 2D
I am getting this error (full traceback shown) when i try and run the code shown below but I do not understand 'ravel' error. I suppose it has something to do with matching coordinates or related between the two plots..? thank you for any help!
Traceback (most recent call last):
File "C:\Users\U321103\.spyder-
py3\MonthlyReport_mapsNCEP_contour_monthly_wspdv2.py", line 85, in <module>
plt.streamplot(lonn[0,:], latt[:,0], diffu, diffv, density=(3.5,3.5),
color='k',linewidth=0.4,arrowsize=0.6)
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Maps\lib\site-
packages\matplotlib\pyplot.py", line 2906, in streamplot
if data is not None else {}))
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Maps\lib\site-
packages\cartopy\mpl\geoaxes.py", line 1897, in streamplot
target_extent=target_extent)
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Maps\lib\site-
packages\cartopy\vector_transform.py", line 146, in vector_scalar_to_grid
return _interpolate_to_grid(nx, ny, x, y, u, v, *scalars, **kwargs)
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Maps\lib\site-
packages\cartopy\vector_transform.py", line 67, in _interpolate_to_grid
s_grid_tuple += (griddata(points, s.ravel(), (x_grid, y_grid),
AttributeError: 'Variable' object has no attribute 'ravel'
I'm looking to solving this same problem and I found an answer to a similar question that help me plotting streamlines and contour togheter. Take a look at here.
In a nutshell, instead of:
plt.streamplot(lonn[0,:], latt[:,0], diffu, diffv, density=(3.5,3.5), color='k',linewidth=0.4,arrowsize=0.6)
You'd use
plt.streamplot(lonn[0,:], latt[:,0], np.array(diffu), np.array(diffv), density=(3.5,3.5), color='k',linewidth=0.4,arrowsize=0.6)
The use of np.array() solves the problem for me.
Best regards,
Mateus
I need to add a horizontal line to the boxplot. Looked through holoviews manual and seems that HLine is supposed to be used in such case. Unfortunately I get an error:
ValueError: all the input arrays must have same number of dimensions
Example:
import numpy as np
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
groups = [chr(65+g) for g in np.random.randint(0, 3, 200)]
boxwhisker = hv.BoxWhisker(
(groups, np.random.randint(0, 5, 200), np.random.randn(200)),
['Group', 'Category'],
'Value'
).sort() * hv.HLine(1)
boxwhisker.opts(
opts.BoxWhisker(
box_color='white',
height=400,
show_legend=False,
whisker_color='gray',
width=600
),
opts.HLine(color='green', line_width=2)
)
layout = hv.Layout(boxwhisker)
hv.save(layout, 'boxplot.html')
Traceback:
File "/home/python3.6/site-packages/holoviews/plotting/renderer.py", line 545, in save
plot = self_or_cls.get_plot(obj)
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/renderer.py", line 135, in get_plot
plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer, **kwargs)
File "/home/python3.6/site-packages/holoviews/plotting/renderer.py", line 207, in get_plot
plot.update(init_key)
File "/home/python3.6/site-packages/holoviews/plotting/plot.py", line 595, in update
return self.initialize_plot()
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/plot.py", line 995, in initialize_plot
subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots)
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/plot.py", line 1115, in initialize_plot
adjoined_plots.append(subplot.initialize_plot(ranges=ranges, plots=passed_plots))
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/element.py", line 2058, in initialize_plot
self._update_ranges(element, ranges)
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/element.py", line 747, in _update_ranges
xfactors, yfactors = self._get_factors(element, ranges)
File "/home/python3.6/site-packages/holoviews/plotting/bokeh/element.py", line 2031, in _get_factors
xfactors = np.concatenate(xfactors)
ValueError: all the input arrays must have same number of dimensions
Yes, HLine is the right way to do this, but unfortunately the support for categorical axes in HoloViews is currently limited and will not allow such an overlay. There's been some work on an unfinished alternative implementation for categorical axes that would fix this. In the meantime, I'd assume you could add a custom hook, but that would be awkward to figure out.
Note that hv.Layout(boxwhisker) won't work as you have it above, in any case; it would need to be hv.Layout([boxwhisker]) or just boxwhisker (as Layout takes a list, but here you don't even need a layout since you have only one item).
I've got a script that takes the output of a separate C++ executable and creates a scatter plot/bifurcation diagram of the resulting data. The application context is to look at angle values versus the driving force by iterating through multiple values of a driving force to get the resulting angle and stroboscopically sampling the results, as a problem regarding a nonlinearly damped driven pendulum from a course on computational physics
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
gbl = 1.0
kappa = 0.5
T_D = 9.424778
ic_ang = 0.1
ic_avel = 0.0
t_final = 200
Nstep = 7500
method = "runge_kutta"
ic_ang = 0.1
Fmin = 0.8
Fmax = 1.6
F_D = float(Fmin)
tstep = T_D/(t_final/Nstep)
Nrep = 3 * tstep
select =[]
step = 0.01
Nite = (Fmax-Fmin)/step
rng = int(Nite-1)
for i in range(rng):
pfile= open('param.dat','w')
pfile.write('%f %f %f %f\n' %(gbl,kappa,F_D,T_D))
pfile.write('%f %f %f\n'%(ic_ang,ic_avel,t_final))
pfile.write('%d %s\n'%(Nstep,method))
pfile.close()
os.system('./a.out > bif.log')
with open("data.out",'r') as datafile:
data=datafile.readlines()
select=data[-Nrep:Nstep:int(tstep)]
for j in select:
plt.plot(F_D, j, "o", color='b', markersize=0.3)
print(F_D,j)
F_D += step
plt.xlabel(r'$F_D$')
plt.ylabel(r'$\theta_{repeat}$')
#plt.xticks([])
plt.yticks([])
plt.show()
However, when I try to run the script I get
Traceback (most recent call last):
File "bif.py", line 45, in <module>
plt.plot(F_D, j, "o", color='b',markersize=0.3)
File"/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/pyt hon/matplotlib/pyplot.py", line 2987, in plot
ret = ax.plot(*args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 4138, in plot
self.add_line(line)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 1497, in add_line
self._update_line_limits(line)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 1508, in
_update_line_limits
path = line.get_path()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/lines.py", line 743, in get_path
self.recache()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/lines.py", line 429, in recache
y = np.asarray(yconv, np.float_)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/numpy/core/numeric.py", line 460, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for float(): 0 0.1 0 0.004995834722
Modifying some of the values to try and debug the script raises a separate exception
Traceback (most recent call last):
File "bif.py", line 24, in <module>
tstep = T_D/(t_final/Nstep)
ZeroDivisionError: float division by zero
I am extremely new to Python so neither one of these exceptions makes much sense to me. However, as Nstep, t_final, and T_D all have finite values, there is no reason (that I can see anyhow) for a dividing by zero error.
I see possible errors for the ValueError as well, as the output in the 1st and 3rd columns (time and angular velocity) aren't float values as they should be. I don't, however, know why these values aren't being converted to a float as they should be.
Any help would be very much appreciated.
EDIT:THIS ISSUE HAS BEEN SOLVED
I think you're asking two questions here, and as I can see the last one about division by zero is the easier one. Namely, the expression t_final/Nstep, as it stands now in your code, is an integer division expression, and the result is 0. Thus the line
tstep = T_D/(t_final/Nstep)
divides by zero.
The second question is why matplotlib complains about the data. To really diagnose this problem we need to look at the content of the data file read by your program. However, I think the problem stems from your attempt to pass text (Python string) to a function expecting numeric data type. When you readlines() the input file, I don't think you're doing any conversion. As a result, a slice of text string is passed to plt.plot and matplotlib struggled to construct a numeric data type from this representation. It would be much better if you read the data, do the proper conversion according to the file format and the logic of your analysis. You may want to look into numpy.loadtxt if it's the case that you're dealing with a text data file.
I am trying to add start points to a streamline plot. I found an example code using start points here; at this link a different issue is discussed but the start_points argument works. From here I grabbed the streamline example code (images_contours_and_fields example code: streamplot_demo_features.py). I don't understand why I can define start points in one code and not the other. I get the following error when I try to define start points in the example code (streamplot_demo_features.py):
Traceback (most recent call last):
File "<ipython-input-79-981cad64cff6>", line 1, in <module>
runfile('C:/Users/Admin/.spyder/StreamlineExample.py', wdir='C:/Users/Admin/.spyder')
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Admin/.spyder/StreamlineExample.py", line 28, in <module>
ax1.streamplot(X, Y, U, V,start_points=start_points)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\__init__.py", line 1891, in inner
return func(ax, *args, **kwargs)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\axes\_axes.py", line 4620, in streamplot
zorder=zorder)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\streamplot.py", line 144, in streamplot
sp2[:, 0] += np.abs(x[0])
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (100,)
I've notice there isn't much on the web in way of using start_points, so any additional information would be helpful.
The main difference between the example that successfully uses start_points and the example from the matplotlib page is that the first uses 1D arrays as x and y grid, whereas the official example uses 2D arrays.
Since the documentation explicitely states
x, y : 1d arrays, an evenly spaced grid.
we might stick to 1D arrays. It's unclear why the example contradicts the docsting, but we can simply ignore that.
Now, using 1D arrays as grid, start_points works as expected in that it takes a 2-column array (first column x-coords, second y-coords).
A complete example:
import numpy as np
import matplotlib.pyplot as plt
x,y = np.linspace(-3,3,100),np.linspace(-3,3,100)
X,Y = np.meshgrid(x,y)
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)
start = [[0,0], [1,2]]
fig0, ax0 = plt.subplots()
strm = ax0.streamplot(x,y, U, V, color=(.75,.90,.93))
strmS = ax0.streamplot(x,y, U, V, start_points=start, color="crimson", linewidth=2)
plt.show()
I'm trying to write a short script that takes a .csv file with some distance data, and outputs the psd file for it. the code is here:
import math
import matplotlib.pyplot as plt
name = raw_input('File:')
data = open(name + '.csv', 'r')
distances = []
for row in data:
distances.append(row.replace("\n",""))
for i in range(len(distances)):
distances[i] = float(distances[i])
Pxx, freqs = plt.psd(distances, NFFT=16,Fs=2,detrend='detrend_mean',window='window_none',noverlap=128,sides='onesided',scale_by_freq=True)
plot(Pxx,freqs)
plt.savefig(name + 'psd.png', bbox_inches = 'tight')
As you can see, it's pretty simple. the csv file just features one column of numbers, so distances is a vector.
The error I'm getting is as follows:
Traceback (most recent call last):
File "C:psdplot.py", line 15, in <module>
Pxx, freqs = plt.psd(distances, NFFT=16,Fs=2,detrend='detrend_mean',window='window_none',noverlap=128,sides='onesided',scale_by_freq=True)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3029, in psd
sides=sides, scale_by_freq=scale_by_freq, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 8696, in psd
sides, scale_by_freq)
File "C:\Python27\lib\site-packages\matplotlib\mlab.py", line 389, in psd
scale_by_freq)
File "C:\Python27\lib\site-packages\matplotlib\mlab.py", line 423, in csd
noverlap, pad_to, sides, scale_by_freq)
File "C:\Python27\lib\site-packages\matplotlib\mlab.py", line 251, in _spectral_helper
assert(len(window) == NFFT)
AssertionError
Could someone direct me on how to fix this? I'm sure it's rather obvious, but I haven't been able to find anything on fixing it in this particular context.
Thanks in advance!