I have a dataset like this but for many ids :
Information = [{'id' : 1,
'a' : array([0.7, 0.5 , 0.20 , 048 , 0.79]),
'b' : array([0.1, 0.5 , 0.96 , 08 , 0.7]))},
{'id' : 2,
'a' : array([0.37, 0.55 , 0.27 , 047 , 0.79]),
'b' : array([0.1, 0.5 , 0.9 , 087 , 0.7]))}]
I would like to plot these in one graph a on x axis and b on y axis for many different ids.
I can make one plot by doing this?
a_info = information[1]['a']
b_info = information [2]['b]
plt.scatter(a_info , b_info)
plt.show()
but how do I do it for all plots?
e = [d['id'] for d in information]
for i in e:
a_info = information[i]['a']
b_info = information [i]['b]
plt.scatter(a_info , b_info)
plt.show()
You can loop over the ids, and create plots for each substructure:
import matplotlib.pyplot as plt
from numpy import array
information = [{'id' : 1, 'a':array([0.7, 0.5 , 0.20 , 0.48 , 0.79]), 'b':array([0.1, 0.5 , 0.96 , 0.8 , 0.7])}, {'id':2, 'a':array([0.37, 0.55, 0.27 , 0.47 , 0.79]), 'b':array([0.1, 0.5 , 0.9 , 0.87 , 0.7])}]
colors = iter(['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'])
for i in information:
plt.scatter(i['a'], i['b'], label = 'id{}'.format(i['id']), color=next(colors))
plt.legend(loc='upper left')
plt.show()
You can loop over all ids and plot them:
for i in Information:
plt.scatter(i['a'], i['b'], label=i['id'])
plt.legend()
plt.show()
Output:
Related
I can plot a 100% stacked bar from Excel. is it possible to achieve the same with matplotlib ?
import pandas as pd
import matplotlib.pyplot as plt
data = [
[0.4 , 0.3 , 0.2 , 0.1],
[0.5 , 0.3 , 0.6 , 0.1],
[0.1 , 0.4 , 0.2 , 0.8],
]
columns = ["A","B","C","D" ]
df = pd.DataFrame(data=data , columns=columns , index = ["Empty" , "Wrong" , "Correct"] )
df.plot(kind="barh" , stacked=True )
plt.ylabel("Percentages")
plt.show()
print (df)
This question already has an answer here:
Prevent scientific notation
(1 answer)
Closed 2 years ago.
I am plotting a simple plot in Matplotlib, Python using the following code:
temp=np.array([1. , 1. , 1. , 1. , 1. ,
1. , 1. , 1. , 1. , 1. ,
1. , 1. , 1. , 1. , 0.99999999,
0.99999999, 0.99999998, 0.99999996, 0.99999993, 0.99999989,
0.99999982, 0.99999972, 0.99999958, 0.99999933, 0.99999906,
0.99999857, 0.99999791, 0.9999971 , 0.99999611, 0.99999459,
0.99999276, 0.99999014, 0.99998735, 0.99998418, 0.99997975,
0.99997557, 0.99997059, 0.9999657 , 0.99996077])
temp2=np.array([0.025, 0.05 , 0.075, 0.1 , 0.125, 0.15 , 0.175, 0.2 , 0.225,
0.25 , 0.275, 0.3 , 0.325, 0.35 , 0.375, 0.4 , 0.425, 0.45 ,
0.475, 0.5 , 0.525, 0.55 , 0.575, 0.6 , 0.625, 0.65 , 0.675,
0.7 , 0.725, 0.75 , 0.775, 0.8 , 0.825, 0.85 , 0.875, 0.9 ,
0.925, 0.95 , 0.975])
plt.plot(temp2,temp)
plt.xlabel(r'$\frac{\tau}{\tau_c}$')
plt.ylabel(r'$\frac{\alpha ^{ss}}{\alpha {_0} ^{ss}}$')
plt.ticklabel_format(style='plain')
plt.rcParams.update({'font.size': 16})
I am getting the following figure in a scientific notation despite specifying the style to be plain.
What is the issue here and how do I resolve this ?
Setting useOffset=False, will do it, like this:
plt.ticklabel_format(style='plain', useOffset=False)
when running this code I have an error
IndexError: only integers, slices (:), ellipsis (...),
numpy.newaxis (None) and integer or boolean arrays are valid indices
python code
import random
def getsys():
row = ''
for i in range(0 , 8):
randintt = str(random.randint(0 , 4))
row += randintt
return row
def getx():
x = []
for i in range(0,14):
mysys = getsys()
x.append(mysys)
return x
y = getx()
print (y)
import initialsys
import numpy as np
R = np.array([[0.90 , 0.93,0.91 , 0.95],
[0.95 , 0.94, 0.93, 0],
[0.85 , 0.90 , 0.87 , 0.92],
[0.83 , 0.87 , 0.85 , 0 ],
[0.94 , 0.93 , 0.95 , 0],
[0.99 , 0.98 , 0.97 , 0.96],
[0.91 , 0.92 , 0.94 , 0],
[0.81 , 0.90 , 0.91 , 0],
[0.97 , 0.99 , 0.96 , 0.91],
[0.83 , 0.85 , 0.90 , 0],
[0.94 , 0.95 , 0.96 , 0],
[0.79 , 0.82 , 0.85 , 0.90],
[0.98 , 0.99 , 0.97 , 0],
[0.85 , 0.92 , 0.95 , 0.99]
])
def expression(r ,possition , char ):
exp = 1-r[possition , char]
x = initialsys.getx()
possition = 1
Total = 1
char = ""
for row in x :
for char in row :
if char!= 0 :
exp = expression(R , possition , char)
Total = Total*exp
Total = 1-Total
possition = possition + 1
For people who are getting this error while doing machine learning coding using numpy. When you are trying to print out the prediction classes[d["Y_prediction_test"][0,index]] you will be getting the same error. Please note that d["Y_prediction_test"][0,index] return a float like 1.0. so you should convert it to int
plt.show()
val = d["Y_prediction_test"][0,index]
val = int(val)
print(classes[val])
I have looked for this answer. But was not able to find it. It took some time to solve this, I hope this will help you. I'm self-learning ML/AI. So if we are in the same team, let's connect and help each. Thanks.
You have a number of problems in your code but to fix your current error you need to index the array with integers as said in the error and not a char, you could do int(char) and then return the result.
def expression(r, possition , char):
return 1-r[possition, int(char)]
I'm writing a Python implementation of Euler's method, using an example from Paul's math notes here.
I'm using a n x 3 numpy array to store the results. The goal is to have the t-value in the first column, y in the second, and the value of y' computed using the current row in the third column.
When I did the first problem listed on the page, using only ten iterations, everything behaved exactly as expected. The step size was 0.1, so the values in the first column incremented by 0.1 with each iteration of the for loop.
But now that I've copied the code over and attempted to apply it to problem 3, the first column behaves very strangely. I inputted the step size as 0.01, but for the first ten iterations it increments by 0.1, then after the tenth iteration it appears to reset to zero, then uses the expected 0.01, but later on it resets again in a similar fashion.
Here's my code:
import numpy as np
def ex3(t,y):
return y + (-0.5 * np.exp(t/2) * np.sin(5*t)) + (5 * np.exp(t/2) * np.cos(5*t))
ex3out = np.empty((0,3), float)
# Input the initial conditions and first y' computation
ex3out = np.append(ex1out, np.array([[0,0,ex3(0,0)]]), axis=0)
h = 0.01
n = 500
for i in range(1,n+1):
# Compute the new t and y values and put in 0 as a dummy y' for now
new = np.array([[ex3out[i - 1,0] + h, ex3out[i - 1,1] + h * ex3out[i - 1,2],0]])
# Append the new row
ex3out = np.append(ex3out,new,axis=0)
# Replace the dummy 0 with y' based on the new values
ex3out[i,2] = ex3(ex3out[i,0],ex3out[i,1])
And here are the first several rows of ex3out after running the above code:
array([[ 0. , 1. , -1. ],
[ 0.1 , 0.9 , 5.2608828 ],
[ 0.2 , 0.852968 , 3.37361534],
[ 0.3 , 0.8374415 , 0.6689041 ],
[ 0.4 , 0.83983378, -2.25688988],
[ 0.5 , 0.85167737, -4.67599317],
[ 0.6 , 0.86780837, -5.90918813],
[ 0.7 , 0.8851749 , -5.51040903],
[ 0.8 , 0.90205891, -3.40904125],
[ 0.9 , 0.91757091, 0.031139 ],
[ 1. , 0.93132436, 4.06022317],
[ 0. , 0. , 5. ],
[ 0.01 , 0.99 , 5.98366774],
[ 0.02 , 0.95260883, 5.92721107],
[ 0.03 , 0.88670415, 5.82942804],
[ 0.04 , 0.84413054, 5.74211536],
[ 0.05 , 0.81726488, 5.65763415],
[ 0.06 , 0.80491744, 5.57481145],
[ 0.07 , 0.80871649, 5.4953251 ],
[ 0.08 , 0.83007081, 5.42066644],
[ 0.09 , 0.8679685 , 5.34993924],
[ 0.1 , 0.9178823 , 5.2787651 ],
[ 0.11 , 0.97192659, 5.19944036],
[ 0.12 , 0.05 , 4.13207859],
[ 0.13 , 1.04983668, 4.97466166],
[ 0.14 , 1.01188094, 4.76791408],
[ 0.15 , 0.94499843, 4.5210138 ],
[ 0.16 , 0.90155169, 4.28666725],
[ 0.17 , 0.87384122, 4.0575499 ],
[ 0.18 , 0.86066555, 3.83286568],
[ 0.19 , 0.86366974, 3.61469476],
[ 0.2 , 0.88427747, 3.40492482],
[ 0.21 , 0.92146789, 3.20302701],
I wondered if this might be a floating point issue, so I tried enclosing various parts of the for loop in float() with the same results.
I must've made a typo somewhere, right?
Simpler loop:
ex3out = [[0, 0, ex3(0,0)]]
h = 0.01
n = 50
for i in range(1,n+1):
# Compute the new t and y values and put in 0 as a dummy y' for now
last = ex3out[-1]
new = [last[0] + h, last[1] + h * last[2], 0]
new[2] = ex3(new[0], new[1])
# Append the new row
ex3out.append(new)
print(np.array(ex3out)) # for pretty numpy display
I have many triangles (say N=10^6) with (x,y,z) coordinates of each vertex of the triangles stored in a file. So each triangle has 9 numbers stored as a row in the file. Hence the file has N rows. Now I just want to plot (in 3d) all the triangles filled with some colour. The triangles may or may not be adjacent. I am very very confused surfing through matplotlib documentation. Kindly help. Don't scold me please.
Plotting 10 million triangles on a plot which has at most 1 million pixels may not make too much sense. In any case, if you do not have information about which vertex is adjacent to which other, you cannot directly use the plot_trisurf method.
I see two options:
Plot a Poly3DCollection.
Filter the unique points from the data and supply those to plot_trisurf. Using this method, you may not be able to colorize the triangles to your wishes, but only according to z-Value.
The following would be an example on how to plot a Poly3DCollection from your input data. For the purpose of demonstration we first need to provide some sample data (this needs to be the duty of the questioner, not the answerer).
import numpy as np
np.set_printoptions(threshold='nan')
phi = np.linspace(0,2*np.pi, 7)
x = np.cos(phi) + np.sin(phi)
y = -np.sin(phi) + np.cos(phi)
z = np.cos(phi)*0.12+0.7
a = np.zeros((len(phi)-1, 9))
a[:,0] = x[:-1]
a[:,1] = y[:-1]
a[:,2] = z[:-1]
a[:,3:6] = np.roll( a[:,0:3], -1, axis=0)
a[:,8] = np.ones_like(phi[:-1])
a = np.around(a, 2)
print a
which prints
[[ 1. 1. 0.82 1.37 -0.37 0.76 0. 0. 1. ]
[ 1.37 -0.37 0.76 0.37 -1.37 0.64 0. 0. 1. ]
[ 0.37 -1.37 0.64 -1. -1. 0.58 0. 0. 1. ]
[-1. -1. 0.58 -1.37 0.37 0.64 0. 0. 1. ]
[-1.37 0.37 0.64 -0.37 1.37 0.76 0. 0. 1. ]
[-0.37 1.37 0.76 1. 1. 0.82 0. 0. 1. ]]
(every set of 3 columns belongs to one point, first column is x, second y, third, z).
Now we can actually build the Poly3Dcollection.
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
fc = ["crimson" if i%2 else "gold" for i in range(a.shape[0])]
poly3d = [[ a[i, j*3:j*3+3] for j in range(3) ] for i in range(a.shape[0])]
ax.add_collection3d(Poly3DCollection(poly3d, facecolors=fc, linewidths=1))
ax.set_xlim(-1.5,1.5)
ax.set_ylim(-1.5,1.5)
plt.show()