How to draw a plot with srveral Gaussuans without any data in Python?
So, I wanna do a spectrum with 4 lines described as gaussian fuctions. I know only their x and y and know how it's supposed to look, but have no data. How do I do a dataset for this plot so that would be arrays for x and y axes? The plot has to look like that: enter image description here
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
How to deal with the colorbar axis space in matplotlib subplots
I am plotting seven different parameters over four seasons, as shown in below image. but on last column (Post-Monsoon) sub_plots axis compromised with colorbar axis, that is really awkward!!
import matplotlib.pyplot as plt import cartopy import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import warnings warnings.filterwarnings('ignore') k = [1,5,9,13,17,21,25] k1= [25,26,27,28] k2= [4,8,12,16,20,24,28] k3= [1,2,3,4] k4=[25] S=['Winter','Pre-monsoon','Monsoon','Post-Monsoon'] fig=plt.figure(figsize=(13,11), dpi=300) for i in range(1,29): ax = fig.add_subplot(7,4,i, projection=ccrs.PlateCarree()) ax.set_extent([39.9,100.5,-0.5,25.5],ccrs.PlateCarree()) ax.add_feature(cartopy.feature.COASTLINE) ax.add_feature(cartopy.feature.BORDERS, linestyle='-') ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k') ax.set_xticks([40,50,60,70,80,90,100], crs=ccrs.PlateCarree()) ax.set_yticks([0,5,10,15,20,25], crs=ccrs.PlateCarree()) ax.tick_params(axis='x', length=7, width=1, bottom=True, top=True) ax.tick_params(axis='y', length=7, width=1, right=True, left=True) ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_major_formatter(plt.NullFormatter()) A=D[i-1].plot.pcolormesh(ax=ax, cmap='seismic', transform=ccrs.PlateCarree(), add_colorbar=False,add_labels=False) # D contains list of parameters to be plotted if i in k: gl = ax.gridlines(draw_labels=True, linestyle='--') gl.xlabels_top=False gl.xlabels_bottom=False gl.ylabels_right=False gl.xformatter=LONGITUDE_FORMATTER gl.yformatter=LATITUDE_FORMATTER gl.xlabel_style={'size':10,} gl.ylabel_style={'size':10,} ax.tick_params(axis='y', length=7, width=1, left=False) if i in k1: gl = ax.gridlines(draw_labels=True, linestyle='--') gl.xlabels_top=False gl.xlabels_bottom=True gl.ylabels_right=False gl.ylabels_left=False gl.xformatter=LONGITUDE_FORMATTER gl.yformatter=LATITUDE_FORMATTER gl.xlabel_style={'size':10,} gl.ylabel_style={'size':10,} ax.tick_params(axis='x', length=7, width=1, bottom=False, top=True) ax.tick_params(axis='y', length=7, width=1, right=True, left=True) if i in k4: ax.tick_params(axis='y', length=7, width=1, right=True, left=False) if i in k2: ax.tick_params(axis='y', length=7, width=1, right=False) fig.colorbar(A,ax=ax, shrink=0.5) # Here is the Colorbar option if i in k3: ax.tick_params(axis='x', length=7, width=1,top=False) ax.title.set_text(S[i-1]) fig.tight_layout(h_pad=0) plt.show()
How to adjust colorbar without distortion of the last axis, Any remark from the community🙏 Thanks
-
Place ipywidget Dropdown on screen in matplotlib.pyplot axes ax1
When I run this code, the Dropdown is nowhere to be found. How do I make it appear in ax1? (I think I would like to avoid Tkinter.)
#!/usr/bin/env python3 #Place ipywidget Dropdown on screen in matplotlib.pyplot axes ax1 import matplotlib.pyplot as plt from ipywidgets.widgets import Dropdown, Layout fig = plt.figure() axcolor = 'lightgoldenrodyellow' # I want a fig with 1 axes--left rectangle with Dropdown (later I will have 4 other axes) # instance the axes [left, bottom, width, height]. ax1 = fig.add_axes([.1, .4, .4, .4]) #([.92, .97, .08, .03]) # Dropdown is from ipywidgets def STypeGrp_event_handler(change): print(change.new) STypeGrp.value = "" STypeGrp = Dropdown( options=list(['E1', 'E2', 'F1']), value='E1', description='Type-Grp:', layout=Layout(width='100px', margin = '20px 20px 20px 20px') ) STypeGrp.observe(STypeGrp_event_handler) #widgets.interact(STypeGrp_event_handler, value=STypeGrp) plots = [STypeGrp] # ?? How do I put STypeGrp dropdown into the ax1 frame?? figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show()
-
Training plot is not appearing properly for keras model
I have data where I need to train it with X and Y. Traning part is done but when I want to plot the prediction and actual data, it is appearing with so many lines instead of showing just non-linear regression line.
model= Sequential() model.add(Dense(7,input_dim=1, activation="tanh")) model.add(Dense(1)) model.compile(loss="mse", optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), metrics= ["mae"]) history=model.fit(X,Y,epochs=1000) predict=model.predict(X) plt.scatter(X, Y,edgecolors='g') plt.plot(X, predict,'r') plt.legend([ 'Predictated Y' ,'Actual Y']) plt.show()
Please see the attached imageplotting image
-
r - Plotting monthly time series data in R - cannot plot more than 10 series
I'm having a lot of trouble plotting my time series data in R Studio. My data is laid out as follows:
tsf
Time Series: Start = 1995 End = 2021 Frequency = 1 Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec 1995 10817 8916 9697 10314 9775 7125 9007 6000 4155 3692 2236 996 1996 12773 12562 13479 14280 13839 9168 10959 6582 5162 4815 3768 1946 1997 14691 12982 13545 14131 14162 10415 11420 7870 6340 6869 6777 6637 1998 17192 15480 14703 16903 15921 13381 13779 9127 6676 6511 5419 3447 1999 13578 19470 23411 18190 18979 17296 16588 12561 10405 8537 7304 4003 2000 20100 29419 30125 27147 27832 23874 19728 15847 11477 9301 6933 3486 2001 16528 22258 22146 19027 19436 15688 14558 10609 6799 6563 4816 2480 2002 14724 19424 21391 17215 18775 13017 14385 10044 7649 6598 4497 2766 2003 17051 20182 18564 18484 15365 12180 13313 8859 6830 6371 3781 2012 2004 16875 20084 21150 19057 16153 13619 14144 9599 7390 5830 3763 2033 2005 20002 24153 23160 20864 18331 14950 14149 11086 7475 6290 3779 2134 2006 24605 26384 24858 20634 18951 15048 14905 10749 7259 5479 3074 1509 2007 29281 26495 25974 21427 20232 15465 15738 10006 6674 5301 2857 1304 2008 32961 24290 20190 17587 12172 7369 16175 6822 4364 2699 1174 667 2009 10996 8793 7345 5558 4840 4833 4355 2422 2272 1596 948 474 2010 10469 11707 12379 9599 8893 8314 7018 5310 4683 3742 2146 647 2011 13624 13470 12390 11171 9359 9240 6953 3653 2861 2216 1398 597 2012 14507 10993 10581 9388 7986 5481 6164 3736 2783 2442 1421 774 2013 10735 9671 10596 8113 7095 3293 9306 4504 3257 2832 1307 639 2014 15975 11906 11485 11757 7767 3390 14037 6201 4376 3082 1465 920 2015 20105 15384 17054 13166 9027 3924 21290 8572 5924 3943 1874 847 2016 27106 21173 20096 14847 10125 4143 22462 9781 5842 3831 1846 679 2017 26668 16905 17180 13427 9581 3585 21316 8105 4828 3255 1594 601 2018 25813 16501 16088 11557 9362 3716 20743 7681 4397 2874 1647 778 2019 22279 14178 14404 13794 9126 3858 18741 7202 4104 3214 1676 729 2020 20665 13263 10239 1338 1490 2189 15329 7360 5747 4189 1468 1032 2021 16948 11672 10672 8214 7337 4980 20232 8563 6354 3882 2167 832
When I attempt rudimentary code to plot the data I get the following
plot(tsf) 'Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, : cannot plot more than 10 series as "multiple"'
My data is monthly and therefore 12 months exceed this apparent limit of 10 graphs.I've been able to make some plot by excluding two months but this is not practical for me. I've looked at lots of answers on this, many of which recommending
ggplot() {ggplot2}
The link below had data most closely resembling my data but I still wasn't able to apply it.
issues plotting multivariate time series in R
Any help greatly appreciated.
-
How to plot a Sequential Bayes Factor as participants are added
I am currently analyzing eye-tracking data using the Sequential Bayes Factor method, and I would like to plot how the resulting Bayes Factor (BF; calculated from average looking times) changes as participants are added.
I would like the x-axis to represent the number of participants included in the calculation, and the y-axis to represent the resulting Bayes Factor.
For example, when participants 1-10 are included, BF = [y-value], and that is one plot point on the graph. When participants 1-11 are included, BF = [y-value], and that is the second plot point on the graph.
Is there a way to do this in R?
For example, I have this data set:
ID avg_PTL <chr> <dbl> 1 D07 -0.0609 2 D08 0.0427 3 D12 0.112 4 D15 -0.106 5 D16 0.199 6 D19 0.0677 7 D20 0.0459 8 d21 -0.158 9 D23 0.0650 10 D25 0.0579 11 D27 0.0463 12 D29 0.00822 13 D30 0.00613 14 D36 -0.0484 15 D37 0.0312 16 D39 0.000547 17 D44 0.0336 18 D46 0.0514 19 D48 0.236 20 D51 -0.000487 21 D60 0.0410 22 D61 0.0622 23 D62 0.0337 24 D64 -0.125 25 D65 0.215 26 D66 0.200
And I calculate the BF with:
bf.mono.correct = ttestBF(x = avg_PTL_mono_correct$avg_PTL)
Any tips are much appreciated!
-
Julia plot hline! doesn't work with multiple threads
I have a simple simulation and I want to plot errors on 3 distinct figures. To speed things up I wanted to introduce a little bit of parallel computing.
Threads.@threads for i in 1:3 plt = plot(t, err[:, i], linecolor=:blue, label=[""], linewidth=3) hline!(plt, [0], linestyle=:dash, linecolor=:black, label=[""]) xlabel!(L"t") ylabel!(L"e_%$i") savefig(plt, "fig/Staubli_Slotine_Li$i.pdf") end
Everything stops working when I try running julia with
-t3
flagERROR: LoadError: TaskFailedException Stacktrace: [1] wait @ ./task.jl:334 [inlined] [2] threading_run(func::Function) @ Base.Threads ./threadingconstructs.jl:38 [3] top-level scope @ ./threadingconstructs.jl:97 nested task error: KeyError: key :annotations not found Stacktrace: [1] pop!(h::Dict{Symbol, Any}, key::Symbol) @ Base ./dict.jl:587 [2] pop_kw!(dd::RecipesPipeline.DefaultsDict, k::Symbol) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/utils.jl:57 [3] _update_subplot_args(plt::Plots.Plot{Plots.PGFPlotsXBackend}, sp::Plots.Subplot{Plots.PGFPlotsXBackend}, plotattributes_in::Dict{Symbol, Any}, subplot_index::Int64, remove_pair::Bool) @ Plots ~/.julia/packages/Plots/nzdhU/src/args.jl:2058 [4] _subplot_setup(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:277 [5] plot_setup!(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:138 [6] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/RecipesPipeline.jl:87 [7] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:208 [8] plot!(::Plots.Plot; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:198 [9] plot!(; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:188 [10] #xlabel!#484 @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [11] xlabel! @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [12] macro expansion @ ~/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:29 [inlined] [13] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})(onethread::Bool) @ Main ./threadingconstructs.jl:85 [14] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})() @ Main ./threadingconstructs.jl:52 in expression starting at /home/jcebulsk/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:26
If I comment out
hline!
the script runs without any issue.It looks like I can't have both
hline
and parallel operation. -
How can I speed up the routing process in OSMNX?
Say I have two taxi orders with Origin1、Destination1 and Origin2、Destination2(O1,O2,D1,D2). I want to calculate the possibility of ridesharing, so I need the path between two different points. And, here's my code:
def path_time(point1, point2): path = ox.distance.shortest_path(road, point1, point2, weight='travel_time') if path is None: #If there isn't a path, a big weight will be set, and it won't be selected during the matching process. route_time = 9999 else: route_time = int(sum(ox.utils_graph.get_route_edge_attributes(road, path, "travel_time"))) return route_time,path
Since there is four points, I need to do this six times, where tp means travel path :
tpO1O2 = path_time(O1,O2) tpO1D1 = path_time(O1,D1) tpO1D2 = path_time(O1,D2) tpO2D1 = path_time(O2,D1) tpO2D2 = path_time(O2,D2) tpD1D2 = path_time(D1,D2)
It's okay if I only have two points, but I got a 2 million order set, and each order has hundreds of potential matched orders. So this will take me a lot of time.
Does anyone knows how can I speed up this process? Thank you!
-
How to properly plot a tree (27k nodes) using a circular tree / leave layout
I have this (unbalanced) tree with 27k+ nodes. It is an hierachy. Now I would to plot it as such to obtain a plot something like this (no idea how you would describe it, but I would call it a circular leave tree...?
However, I am unable to achieve such a result unfortunately. I have already tried
igraph
,Networkx
,Maltego
,Graphviz
,Gephi
. Hopefully someone can help me / give me tips & tricks or hints.Maltego
Gives me quiet easily the following. However I cannot export it to pdf. Furthermore it has this wierd expansion on the top going to the left. I would be able to 'manually' (minimize) move it. However that is not what I would like.
This is btw in my view (with the manual fix) the best result. But I cannot export it to vector or high-res image.
igraph
import igraph as ig bigGraphAsTupleList = (('a','b'),('b','c'),('b','d'), ..., ('c','e')) g = ig.Graph.TupleList(bigGraphAsTupleList) layout = g.layout("rt_circular") #fr (fruchterman reingold), tree, circle, rt_circular (reingold_tilford_circular) # bbox = size of picture ig.plot(g,layout=layout,bbox=(10000,10000),target='mygraph.png')
This gives me something like below.
fruchterman reingold (so much overlap of nodes and connections)
Networkx
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_edge(...) #build graph nx.draw_circular(G) #nx.draw_spring(G) #nx.draw_spectral plt.draw() plt.show()
Graphviz (via Networkx)
Also a wierd result a bit similar as the next one Maltego. However
import networkx as nx import matplotlib.pyplot as plt import pydot from networkx.drawing.nx_pydot import graphviz_layout G = nx.Graph() G.add_edge(...) #build graph pos = graphviz_layout(G, prog="circo") plt.figure(1,figsize=(60,60)) nx.draw(G, pos,node_size=10) plt.show(block=False) plt.savefig("Graph.png", format="PNG")
-
Object and Pointers Graph Representation in Ruby
I am studying how to represent a graph in memory with Objects and Pointers in ruby and cannot find a representation of this anywhere. Can anyone point me in the right direction of how to build this ds?
-
How to make gaussian distribution in pytorch?
I want to make probability like
torch.bernoulli()
this function. Has any solution?
-
Pdf of product of two i.i.d random variable distributed as circular symmetric gaussian
what is a distribution of the product of two circular symmetric Gaussian random variables?