Plotting only specific points using matplotlib's imshow
import numpy as np import matplotlib.pyplot as plt N = 101 x = np.linspace(-1,1,N); ones = np.ones_like(x) coords = np.outer(ones,x) #x coords coords = np.concatenate([[coords], [coords.T]]) ourShape = np.zeros([N,N]) ourShape[np.square(coords[0,:,:]) + np.square(coords[1,:,:]) <= 1.] = 1. fig, ax = plt.subplots(); ax.imshow(ourShape) plt.show()
This plots a circle inscribed in a square. But how do I get python to plot only the blue region, which is part of the square and not the circle? To be clear, I do not want to just turn the circle white; I want it to not plot at all. I tried
ax.imshow(ourShape[ourShape < 1.])
and that produces a TypeError.
See also questions close to this topic
Url parameter to model field
I have a view that takes a parameter and returns a csv file based on a queryset:
def rfidi_list(request, id=None): if id == None: raise Http404 rfid_list = Rfid.objects.filter(----).values_list('rfid_st', flat=True) import csv response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="rfidi_list.csv"' writer = csv.writer(response, delimiter=';') writer.writerow(rfid_list) return response
I have a model called Rfid that has boolean fields named: vrata1, vrata2, vrata3
I want to filter queryset based on the id that came in url. If the id was 1, I would return objects with vrata1 = True, if it was 2 I'd like to get qs with objects with vrata2 = True.
C program to manupulate the bunarh no and check the accourence of 0 and 1
You are provided with a number N containing only digits "1" and "0". The idea is to make the number to have all the digits same. For that, you can only change exactly one digit, either "0" to "1" or "1" to "0". If it is possible to make all the digits same by flipping exactly one digit then print "YES" else "NO".
Input: A number made up of only digits "1" and "0".
Output: Print "YES" if it is possible to make all the digits same else "NO" without quotes.
Plz help me out ....how can we initialize binary number to a integre variable
unable to import pandas
I installed some backtesting libraries which updated pandas version.
Since then I'm getting
ImportError: cannot import name 'hashtable'
I referred the existing question: Hashtable Error in Pandas.
> pip install pandas > conda update pandas
but nothing seems working. Any suggestions are welcome.
I removed pandas from conda using
conda remove --force pandasAnd reinstalled it. Now I'm getting new error
AttributeError: module 'pandas' has no attribute 'compat'
How to calculate rise in of the vectors in 3D which are tilted?
I have a data, which shows coordinates for start and end of the vectors in 3D space which are orientated around 3-fold screw axis:
x y z 0 38.522003 5.600998 129.203995 # start of v1 1 23.854996 66.576996 112.487000 # end of v1 2 4.417000 40.182999 121.309998 # start of v2 3 65.761993 27.550995 104.285004 # end of v2 4 50.272003 56.473999 112.857010 #... 5 12.574997 6.202995 96.598007 6 45.192993 8.042999 105.147995 7 15.934998 63.490005 88.347992 8 3.613998 33.112991 97.102997 9 66.244003 35.949997 80.309006 10 44.052994 59.996002 89.057999 11 19.916000 2.125000 72.294998 12 51.201996 11.974998 81.044998 13 9.035995 58.367996 64.238998 14 4.529999 25.854996 72.759003 15 64.563004 44.283997 56.357998 16 37.153000 62.003998 65.026001 17 28.061996 0.000000 48.126995
for i in range(xyz_coords.shape): if i == 0: ax.plot(xyz_coords['x'].loc[0:1], xyz_coords['y'].loc[0:1], xyz_coords['z'].loc[0:1]) elif i%2 == 0 and i!=0: ax.plot(xyz_coords['x'].loc[i:i+1], xyz_coords['y'].loc[i:i+1], xyz_coords['z'].loc[i:i+1])
I would like to calculate the rise and angle between each starting and ending positions of the vector in relation to the next one, and those values should be similar for each vn and vn+1. The problem is that vectors shifts are not parallel to the z axis - otherwise it would be very simple task to determine the rise. The distance between v1(start) and v2(start) gives me the distance between them. Loading the data given above as pandas DataFrame, the distance between the starting points of v1 and v2:
d = np.sqrt((xyz_coords['x'] - xyz_coords['x'])**2 + (xyz_coords['y'] - xyz_coords['y'])**2 + (xyz_coords['z'] - xyz_coords['z'])**2)
You might also notice, that the z difference is ~8.95 but as as said before, z-difference is not proper rise value because is influenced by the tilt. If I knew how to determine the tilt angle I would be able to calculate the rise by just using
z_prop = sin(tilt_angle) * d. Is there any easy way to correct the tilt and get the proper z value?
How to plot dotted lines from a shapefile in python?
I am not sure on how to plot a dotted line from a shapefile in Python. It appears that readshapefile() does not have any linestyle for me to set. Below I have a working code where I take a shapefile and plot it, but it only plots a solid line. Any ideas to set me in the right direction? Thanks!
The shapefile can be found here: http://www.natice.noaa.gov/products/daily_products.html, where the Start Date is Feb 15th, end date is Feb 17th, and the Date Types is Ice Edge. It should be the first link.
#!/awips2/python/bin/python from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(llcrnrlon=-84.37,llcrnrlat=42.11,urcrnrlon=-20.93,urcrnrlat=66.48, resolution='i', projection='tmerc', lat_0 = 55., lon_0 = -50.) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='#ddaa66',lake_color='aqua') map.drawcoastlines(zorder = 3) map.readshapefile('nic_autoc2018046n_pl_a', 'IceEdge', zorder = 2, color = 'blue') plt.show()
Contour data rotation in python in dicom image
I have a huge data text file. I plot these data on a CT image which results can be seen on the below image. But how could I rotate my dose data axis to be same with my CT image ?
My code so far:
%matplotlib notebook import numpy as np import dicom import matplotlib.pyplot as plt from itertools import islice import matplotlib.colors as colors import matplotlib.cm as cm data = dicom.read_file("NEW.dcm") plt.set_cmap("gray") pixel_array = data.pixel_array plt.pcolormesh(pixel_array) plt.gca().set_aspect("equal") plt.show() CS=plt.contour(xi,yi,zi,cmap=plt.cm.jet) import numpy as np import matplotlib.pyplot as plt a = np.loadtxt('New.txt') i = a[:,1] j = a[:,2] energies = a[:,3] xi = np.linspace(i.min(), i.max()) yi = np.linspace(j.min(), j.max()) zi = scipy.interpolate.griddata((i, j), energies, (xi[None,:], yi[:,None]), method='cubic') fig = plt.figure() CS=plt.contour(xi, yi, zi,colors='k', norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
30 1 2 0.00951305 30 1 3 0.0110269 30 1 4 0.0141366 30 1 5 0.00468656 30 1 6 0.0144487 30 1 7 0.0253241 30 1 8 0.0239877 30 1 9 0.0175475 30 1 10 0.0134009 …
(Full code and data available here)
Superimpose new ax object on existing axes using plt subplots - Matplotlib
I want to superimpose a peakmodel i get from a calculation to existing experimental data to compare it to the fit i did.
No i found a way to do this, by simply plot over the data calling the axes object in question again and plot over it. This happens if you set add_plot=True in the code below:
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Funcitons to model and create data def func(x, a, x0, sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) def func2(x, a, x0, sigma,Points,Range=,ax=None): if not Range: Range =[np.min(x),np.min(x)] x_coordinates = np.linspace(np.min(Range), np.max(Range),Points) Peak=a*np.exp(-(x-x0)**2/(2*sigma**2)) ax = plt.plot(x_coordinates, Peak, label='Simulation',color= "red",linewidth=2) return ax my_dpi=96 nrows=3 Mytext="label" plt.rcParams["axes.linewidth"] = 2 plt.rcParams["patch.linewidth"] = 2 nrows=3 fig, axes = plt.subplots(nrows=nrows, sharex=True, sharey=True, figsize= (500./my_dpi, 400./my_dpi), dpi=my_dpi) # Generating clean data Points=500 x = np.linspace(0, 10, Points) y = func(x, 1, 5, 2) # Adding noise to the data yn = y + 0.2 * np.random.normal(size=len(x)) colors = ('k', 'r', 'b') for ax, color in zip(axes, colors): ax.scatter(x, yn) ax.set_xlim([0,10]) ax.plot(x, y, c='k', label='Func original',linewidth=5) ax.set_yticklabels() ax.set_xlim([max(x),min(x)]) ax.get_yaxis().set_tick_params(which='major',length=3,width=2, direction='in',color='black', left=True, right=True,labelleft=False,labelright=False) ax.get_xaxis().set_tick_params(which='major',length=3,width=2, direction='in',color='black',labeltop=False,bottom=True, top=True) ax.minorticks_on() ax.get_xaxis().set_tick_params(which='minor', length=3, width=2,color='black',direction='in',bottom=True, top=True) ax.tick_params(axis='y',which='minor',left='off') add_plot=True if add_plot==True: axes .plot(x, y, label='Func new axis',color="green") # This works add_to_ax=False if add_to_ax==True: # This seems to also do what it should but i can not chosse the ax object on wich the plot is superimposed. func2(x, 1, 5, 2,Points=500,Range=[0,10],ax=axes) #fig.savefig('model_and_noise.png') plt.show()
The result is this:
I do however want to return a new ax object from a function that contains allot of different stuff and superimpose it to any of the axes objects in the stacked plot without changing any of the x or y axes settings/prams. I almost manged to do what i want, but i can´t seem to choose the axis object, it is always ploted on top of the lowest subplot. This happens if you set add_to_ax=True in the code above:
It should be ploted ontop of the top graph tho.
Thank you in advance
Editable plots in PowerPoint from python: equivalent of officer and rvg
I am using the
rvgpackages to get plots from R into MS PowerPoint as editable vector graphics. Reproducible example below.
I am looking for a way to implement an equivalent solution with python, preferably using
matplotlib. The critical part is not the creation of slides from the IDE but rather the editable vector graphics part, i.e. plots should end up in PowerPoint as grouped objects comprised of a range of simple powerpoint geometries such as lines, squares, and text fields.
library(tidyverse) library(officer) library(rvg) # Get some data and make a plot ggp <- diamonds %>% group_by(clarity) %>% summarise(price = mean(price)) %>% ggplot(aes(x = clarity, y = price, fill = clarity)) + geom_bar(stat = 'identity', colour = 'black') # Create a new powerpoint document doc <- read_pptx() doc <- add_slide(doc, 'Title and Content', 'Office Theme') # Add the plot doc <- ph_with_vg(doc, ggobj = ggp, type = 'body') # Write the document to a file print(doc, target = 'plots.pptx')
The resulting chart is completely editable:
How to change xlab and ylab in diagnostics function in R BAS package
For this function R: https://www.rdocumentation.org/packages/BAS/versions/1.4.7/topics/diagnostics, From BAS v1.4.7 by Merlise Clyde:
I have the previous plot that specified another xlab and lab.
Then when I call this specific diagnostics function, which outputs a plot, I cannot change specify/change the xlab and ylab in the "plot" function embedded within this diagnostics() function From BAS.
How to change xlab and ylab in diagnostics function in R BAS package?