mplot3d gives blank graph but no error - python

So I am trying to plot a 3d chart using mplot3d with matplotlib. Code as following:
# generate the graph
# vols is a 2D array indexed by [maturity, strike].
def DrawGraph(self, strikes, maturities, vols):
import matplotlib.dates as dates
import matplotlib.pyplot as pyplot
# prepare data
Y = dates.date2num(maturities)
X, Y = numpy.meshgrid(strikes, Y)
# plot
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, vols)
pyplot.show()
Where maturities and strikes are 1D arrays, and vols is a 2D array with proper size.
Everything runs proper and all data are valid. However, I got a totally blank window with nothing but gray background.
Anyone can give me some hints of what's going on? I suspect the version of matplotlib isn't right but not sure how to check it.
Thanks in advance.

In the version of matplotlib I have (1.2.1) the projection="3d" will raise an error unless you also include:
from mpl_toolkits.mplot3d import Axes3D
The only thing I can't check is the line
Y = dates.date2num(maturities)
As I am unfamiliar with what data type date2num expects, do you have any sample data?
Other than this everything works fine for me

What about
matplotlib.pyplot.ioff()
That solved my "nothing but gray background"-problem with mplot3d.

Related

Matplotlib alternative to fill_betweenx()

I'm trying to get the functionality of fill_betweenx() without having to use the function itself, because it doesn't accept the interpolate parameter. I need the interpolate functionality that is supported by fill_between(), but for the filling to happen relative to the x axis. It sounds like the interpolate parameter will be supported for fill_betweenx() in matplotlib 2.1, but it would be great to have access to the functionality via a workaround in the meantime.
This is the line of code in question:
ax4.fill_betweenx(x,300,p, where=p>=150, interpolate=True, facecolor='White', lw=1, zorder=2)
Unfortunately this gives me AttributeError: Unknown property interpolate.
One lazy way to do it is to use the fill_between() function with inverted coordinates on a figure that you don't show (i.e. close the figure before using plt.show()), and then re-use the vertices of the PolyCollection that fill_between() returns on your actual plot. It's not perfect, but it works as a quick fix. Here an example of what I'm talking about:
from matplotlib import pyplot as plt
from matplotlib.collections import PolyCollection
import numpy as np
fig, axes = plt.subplots(nrows = 2, ncols =2, figsize=(8,8))
#the data
x = np.linspace(0,np.pi/2,3)
y = np.sin(x)
#fill_between without interpolation
ax = axes[0,0]
ax.plot(x,y,'k')
ax.fill_between(x,0.5,y,where=y>0.25)
#fill_between with interpolation, keep the PolyCollection
ax = axes[0,1]
ax.plot(x,y,'k')
poly_col = ax.fill_between(x,0.5,y,where=y>0.25,interpolate=True)
#fill_betweenx -- no interpolation possible
ax = axes[1,0]
ax.plot(y,x,'k')
ax.fill_betweenx(x,0.5,y,where=y>0.25)
#faked fill_betweenx:
ax = axes[1,1]
ax.plot(y,x,'k')
#get the vertices from the saved PolyCollection, swap x- and y-values
v=poly_col.get_paths()[0].vertices
#convert to correct format
v2=list(zip(v[:,1],v[:,0]))
#and add to axes
ax.add_collection(PolyCollection([v2]))
#voila
plt.show()
The result of the code looks like this:

Zoom an inline 3D matplotlib figure *without* using the mouse?

This question explains how to change the "camera position" of a 3D plot in matplotlib by specifying the elevation and azimuth angles. ax.view_init(elev=10,azim=20), for example.
Is there a similar way to specify the zoom of the figure numerically -- i.e. without using the mouse?
The only relevant question I could find is this one, but the accepted answer to that involves installing another library, which then also requires using the mouse to zoom.
EDIT:
Just to be clear, I'm not talking about changing the figure size (using fig.set_size_inches() or similar). The figure size is fine; the problem is that the plotted stuff only takes up a small part of the figure:
The closest solution to view_init is setting ax.dist directly. According to the docs for get_proj "dist is the distance of the eye viewing point from the object point". The initial value is currently hardcoded with dist = 10. Lower values (above 0!) will result in a zoomed in plot.
Note: This behavior is not really documented and may change. Changing the limits of the axes to plot only the relevant parts is probably a better solution in most cases. You could use ax.autoscale(tight=True) to do this conveniently.
Working IPython/Jupyter example:
%matplotlib inline
from IPython.display import display
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)
# Plot a basic wireframe.
ax.view_init(90, 0)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.close()
from ipywidgets import interact
#interact(dist=(1, 20, 1))
def update(dist=10):
ax.dist = dist
display(fig)
Output
dist = 10
dist = 5

Filling region between curve and x-axis in Python using Matplotlib

I am trying to simply fill the area under the curve of a plot in Python using MatPlotLib.
Here is my SSCCE:
import json
import pprint
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))
fig2, ax2 = plt.subplots()
ax2.fill(x, y)
plt.savefig('picForWeb.png')
plt.show()
The attached picture shows the output produced.
Does anyone know why Python is not filling the entire area in between the x-axis and the curve?
I've done Google and StackOverflow searches, but could not find a similar example. Intuitively it seems that it should fill the entire area under the curve.
I usually use the fill_between function for these kinds of plots. Try something like this instead:
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))
fig, (ax1) = plt.subplots(1,1);
ax1.fill_between(x, 0, y)
plt.show()
See more examples here.
If you want to use this on a pd.DataFrame use this:
df.abs().interpolate().plot.area(grid=1, linewidth=0.5)
interpolate() is optional.
plt.fill assumes that you have a closed shape to fill - interestingly if you add a final 0 to your data you get a much more sensible looking plot.
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791,0]
x = np.arange(len(y))
fig2, ax2 = plt.subplots()
ax2.fill(x, y)
plt.savefig('picForWeb.png')
plt.show()
Results in:
Hope this helps to explain your odd plot.

matplotlib plotting multiple lines in 3D

I am trying to plot multiple lines in a 3D plot using matplotlib. I have 6 datasets with x and y values. What I've tried so far was, to give each point in the data sets a z-value. So all points in data set 1 have z=1 all points of data set 2 have z=2 and so on.
Then I exported them into three files. "X.txt" containing all x-values, "Y.txt" containing all y-values, same for "Z.txt".
Here's the code so far:
#!/usr/bin/python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import pylab
xdata = '/X.txt'
ydata = '/Y.txt'
zdata = '/Z.txt'
X = np.loadtxt(xdata)
Y = np.loadtxt(ydata)
Z = np.loadtxt(zdata)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X,Y,Z)
plt.show()
What I get looks pretty close to what I need. But when using wireframe, the first point and the last point of each dataset are connected. How can I change the colour of the line for each data set and how can I remove the connecting lines between the datasets?
Is there a better plotting style then wireframe?
Load the data sets individually, and then plot each one individually.
I don't know what formats you have, but you want something like this
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
datasets = [{"x":[1,2,3], "y":[1,4,9], "z":[0,0,0], "colour": "red"} for _ in range(6)]
for dataset in datasets:
ax.plot(dataset["x"], dataset["y"], dataset["z"], color=dataset["colour"])
plt.show()
Each time you call plot (or plot_wireframe but i don't know what you need that) on an axes object, it will add the data as a new series. If you leave out the color argument matplotlib will choose them for you, but it's not too smart and after you add too many series' it will loop around and start using the same colours again.
n.b. i haven't tested this - can't remember if color is the correct argument. Pretty sure it is though.

Matplotlib 3D plot doesn't plot correctly

I'm having a problem trying to plot a series of lines in a 3D plot in MatPlotLib.
When I run the code below all the lines are plotted at the last value of y??? Even though y is correctly incremented in the loop.
Any Help understanding this would be appreciated.
Thanks
David
#========== Code Start=================
import numpy as np
import matplotlib
from matplotlib.figure import Figure
import pylab as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x=np.arange(5)
y=np.zeros(len(x))
for i in range(1,10):
y.fill(i)
z=plt.randn(len(y))
ax.plot(xs=x, ys=y, zs=z)#, zdir='z', label='ys=0, zdir=z')
plt.draw()
print i,len(y),y,x,z
plt.xlabel('X')
plt.ylabel('Y')
plt.zlabel('Z')
plt.show()
#========== Code End=================
It looks like y might be pointed to by all plots. So you are passing the reference to y when you execute ax.plot. It is the same reference each time, but the values are changed on each pass. When the plt.show() is executed the reference to y is used and it is now set at 9. So, create a different object for y on each pass with the values you want for that pass:
y = np.zeros(len(x))
y.file(i)
There might be a numpy command that fills with the value you want in one go, but you get the picture.

Categories