Right, so I've got a list of x values, y values and z values (which I think I converted into arrays?) which I want to make a surface plot, but it's not working.
Here's what I'm trying to do, you can ignore most of the code as it is pretty irrelevant - just look at the end where I have xdis, ydis and dist and where I'm trying to plot atm I'm getting ValueError: need more than 1 value to unpack :(. Help much appreciated.
from math import *
from numpy import *
import pylab
def sweep (v,p,q,r,s):
a=.98
for i in range (1, len(v)-1):
for j in range (1, len(v)-1):
c =0.0
if i==p and j==q: c =1.0
if i==r and j==s: c= -1.0
v[i,j]=(v[i -1,j]+v[i+1,j]+v[i,j -1]+v[i,j+1]+c-a*v[i,j])/(4-a)
def main():
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
ydis=[]
xdis=[]
resis=[]
for j in range(2,18):
for i in range(2,18):
v= zeros ((20,20),float )
p=q=9
r=i
s=j
dv =1.0e10
lastdv =0
count =0
while (fabs(dv - lastdv)>1.0e-7*fabs(dv)):
lastdv =dv
sweep(v,p,q,r,s)
dv=v[p,q]-v[r,s]
resis.append(dv)
xdis.append(r-p)
ydis.append(s-q)
X=array(xdis)
Y=array(ydis)
Z=array(resis)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X,Y,Z)
plt.show()
main()
plot_wireframe expects three 2D-arrays (X,Y,Z) as input. So,
after:
X=np.array(xdis)
Y=np.array(ydis)
Z=np.array(resis)
add:
X=X.reshape((-1,16))
Y=Y.reshape((-1,16))
Z=Z.reshape((-1,16))
It doesn't seem like the "sweep" function is modifying 'v' so you're getting an empty list.
Related
Can someone explain why I get this strange output when running this code:
import matplotlib.pyplot as plt
import numpy as np
def x_y():
return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
plt.plot(x_y())
plt.show()
The output:
Your data is a tuple of two 1000 length arrays.
def x_y():
return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
xy = x_y()
print(len(xy))
# > 2
print(xy[0].shape)
# > (1000,)
Let's read pyplot's documentation:
plot(y) # plot y using x as index array 0..N-1
Thus pyplot will plot a line between (0, xy[0][i]) and (1, xy[1][i]), for i in range(1000).
You probably try to do this:
plt.plot(*x_y())
This time, it will plot 1000 points joined by lines: (xy[0][i], xy[1][i]) for i in range 1000.
Yet, the lines don't represent anything here. Therefore you probably want to see individual points:
plt.scatter(*x_y())
Your function x_y is returning a tuple, assigning each element to a variable gives the correct output.
import matplotlib.pyplot as plt
import numpy as np
def x_y():
return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
x, y = x_y()
plt.plot(x, y)
plt.show()
I tried to plot a bar figure and I want x-label to remain the specific order, so I use set_xticklabels. However, the result turns out the y-value didn't match the x-label.
import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(A, B)
ax1.set_xticklabels(A)
plt.title("Animals")
plt.show()
The expected result is Dog=26 Cat=39 Fish=10 Bird=20, but the result I got is Dog=20 Cat=39 Fish=26 Bird=20.
Here is one answer I found. However, if I use this method I cannot keep the original order I want.
import itertools
import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
lists = sorted(itertools.izip(*[A, B]))
new_x, new_y = list(itertools.izip(*lists))
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(new_x, new_y )
ax1.set_xticklabels(new_x)
plt.title("Animals")
plt.show()
Is there any way I can keep the original order of x-label and make y value match with x?
This code will serve the purpose,
import numpy as np
import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
y_pos = np.arange(len(A))
plt.bar(y_pos, B)
plt.xticks(y_pos, A)
plt.title("Animals")
plt.show()
Why don't you use pandas for storing your data:
import pandas as pd
import matplotlib
A= ['Dog','Cat','Fish','Bird']
B= [26,39,10,20]
ser = pd.Series(index=A, values=B)
ax = ser.loc[A].plot(kind='bar', legend=False)
ax.set_ylabel("Value")
ax.set_xlabel("Animals")
plt.show()
In matplotlib 2.2 you can just plot those lists as they are and get the correct result.
import matplotlib.pyplot as plt
A=['Dog','Cat','Fish','Bird']
B=[26,39,10,20]
plt.bar(A, B)
plt.title("Animals")
plt.show()
I have this code :
import numpy as np
import pylab as plt
a = np.array([1,2,3,4,5,6,7,8,9,10])
b = np.exp(a)
plt.plot(a,b,'.')
plt.show()
The code works fine, but I need to modify the x-axis labels of the plot.
I would like the x-axis labels to be all powers of 10 according to the a axis inputs. for the example code, it would be like [10^1, 10^2, ..., 10^10].
I would appreciate any suggestions.
Thank you !
import numpy as np
import pylab as plt
a = np.array([1,2,3,4,5,6,7,8,9,10])
# this is it, but better use floats like 10.0,
# a integer might not hold values that big
b = 10.0 ** a
plt.plot(a,b,'.')
plt.show()
This code probably is what you need:
import numpy as np
import pylab as plt
a = np.asarray([1,2,3,4,5,6,7,8,9,10])
b = np.exp(a)
c = np.asarray([10**i for i in a])
print(list(zip(a,c)))
plt.xticks(a, c)
plt.plot(a,b,'.')
plt.show()
By using plt.xtick() you can customize your x-label of plot. I also replaced 10^i with 10**i.
I am plotting 2D numpy arrays using
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3])
y = np.array([[2,2.2,3],[1,5,1]])
plt.plot(x,y.T[:,:])
plt.legend()
plt.show()
I want a legend that tells which line belongs to which row. Of course, I realize I can't give it meaningful names, but I need some sort of unique label for the line without running through loop.
import numpy as np
import matplotlib.pyplot as plt
import uuid
x = np.array([1,2,3])
y = np.array([[2,2.2,3],[1,5,1]])
fig, ax = plt.subplots()
lines = ax.plot(x,y.T[:,:])
ax.legend(lines, [str(uuid.uuid4())[:6] for j in range(len(lines))])
plt.show()
(This is off of the current mpl master branch with a preview of the 2.0 default styles)
I am quite a beginner in coding ... Im trying to plot curves from 2columns xy data with full line not scatter. I want y to be colored according to the value of y.
I can make it work for scatter but not for line plot.
my code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
read data ... (data are xy 2 columns so one can simply use 2 lists, say a and b)
# a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
# b = [11,12,3,34,55,16,17,18,59,50,51,42,13,14,35,16,17]
fig = plt.figure()
ax = fig.add_subplot(111)
bnorm = []
for i in b:
i = i/float(np.max(b)) ### normalizing the data
bnorm.append(i)
plt.scatter(a, b, c = plt.cm.jet(bnorm))
plt.show()
with scatter it works ...
how can I make it as a line plot with colors ? something like this: