Move 3D plot to avoid clipping by margins

2024/10/14 22:19:24

I'm trying to figure out how I can get the 3D matplotlib images below to plot higher on the canvas so it doesn't get clipped. Here is the code I'm using to create the plot. I couldn't find a way to attach the text file containing the Z elevations (referenced in the code below), but it is simply a 2D array containing a surface made up of values ranging between 0 and 1.

import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3Dnrow=30
ncol=100f = open(r'C:\temp\fracEvapCume_200.txt','r')
fracEvapTS = np.loadtxt(f)
f.close()X, Y = np.meshgrid(ncol, nrow)
Y3d, X3d = np.mgrid[0:Y, 0:X]fig = plt.figure()
ax = fig.gca(projection='3d')
ax.auto_scale_xyz([0, 100], [0, 30], [0, 0.2])
Y3d, X3d = np.mgrid[0:Y, 0:X]
Z = fracEvapTSsurf = ax.plot_surface(X3d, Y3d, Z, cmap='autumn', cstride=2, rstride=2)
ax.set_xlabel("X-Label")
ax.set_ylabel("Y-Label")
ax.set_zlabel("Z-Label")
ax.pbaspect = [1., .33, 0.25]
ax.dist  = 7
plt.tight_layout()
plt.savefig('clipped.png')

In order to get the ax.pbaspect=[1., .33, 0.25] line to work, changes to the get_proj function inside site-packages\mpl_toolkits\mplot3d\axes3d.py were made as suggested in this post. In order to get the figure to draw larger, I added ax.dist = 7 based on this post. Lastly, based on this post I was hoping that plt.tight_layout() would roll back the margins and prevent the red/yellow surface shown below from being clipped, but that didn't work either. I'm failing to find the command that will move the image up on the canvas, thereby avoiding all of the unnecessary white space at the top of the figure and preventing the red/yellow surface from getting clipped. Is there one line of Python that will accomplish this?

enter image description here

after adding the line plt.tight_layout(), it made matters worse:

enter image description here

Answer

The problem is that your modification to site-packages\mpl_toolkits\mplot3d\axes3d.py changes the projection matrix, without changing the center of the view, messing up the position of the scene once transfomed in camera coordinates.

So when the view is zoomed (with ax.dist) then moved, the plot sometimes gets out of the canvas.

enter image description here

You need to replace the following line to the get_proj function in axes3d.py :

    # look into the middle of the new coordinatesR = np.array([0.5, 0.5, 0.5])

By :

    # look into the middle of the new coordinatestry:R = np.array(self.pbaspect)/2except AttributeError:R = np.array([0.5, 0.5, 0.5])

And this should work :

enter image description here

PS : Code used to make the figures :

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3Dnrow=30
ncol=100X, Y = np.meshgrid(ncol, nrow)
Y3d, X3d = np.mgrid[0:Y, 0:X]
Z = np.sin(Y3d/Y)*np.sin(X3d/X)fig = plt.figure()
for i in range(4):ax = fig.add_subplot(2,2,i,projection='3d')ax.auto_scale_xyz([0, 100], [0, 30], [0, 0.2])surf = ax.plot_surface(X3d, Y3d, Z, cmap='autumn', cstride=2, rstride=2)ax.set_xlabel("X-Label")ax.set_ylabel("Y-Label")ax.set_zlabel("Z-Label")ax.pbaspect = [1., .33, 0.25]ax.dist  = 7
https://en.xdnf.cn/q/117902.html

Related Q&A

HTML Link parsing using BeautifulSoup

here is my Python code which Im using to extract the Specific HTML from the Page links Im sending as parameter. Im using BeautifulSoup. This code works fine for sometimes and sometimes it is getting st…

XML format change using XSL file in a Python code

Have written a Python code to transform a XML file to a particular format using XSL stylesheet. Python code below:#!/usr/bin/env python # -*- coding:utf-8 -*- from lxml import etree def transform(xmlP…

How to extract a specific value from a dictionary in python

I want to extract distance from google distance matrix API in Python. The objet it returned is a python dictionary.{destination_addresses: [Mumbai, Maharashtra, India ],origin_addresses: [Powai, Mumbai…

label on top of image in python

I am trying to display text on top of an image. Right now the text is below the image or if I put a row=0 in the grid disappears. I am assuming it is behind the image. I cant seem to get it to work. My…

plot multiple graphs from multiple files gnuplot

I have a set of files named like this:qd-dPZ-z1-1nn.dat qd-dPZ-z2-1nn.dat qd-dPZ-z4-1nn.dat qd-dPZ-z8-1nn.dat qd-dPZ-z16-1nn.dat qd-dPZ-z32-1nn.dat qd-dPZ-z1-2nn.dat qd-dPZ-z2-2nn.dat qd-dPZ-z4…

Python writing to CSV... TypeError: coercing to Unicode: need string or buffer, file found

outputList is a list of lists. [ [a,b,c], [d,e,f], [g,h,i] ] and I want to output it to a csv file with each list as a separate row. Im getting this error TypeError: coercing to Unicode: need string or…

Preserve Signature in Decorator python 2

I am writing a decorator which will catch TypeError for incorrect number of arguments in a function call and will print a customised message. The code is here:import inspectdef inspect_signature(f):def…

Gimp: start script without image

Well, Im trying to write a python plug-in for Gimp, but it wont start without first loading an image... What can I do about that?

Pywinauto: how the `findbestmatch` module works?

Im trying to understand how the findbestmatch module works. Here is an example.from pywinauto.application import Application from pywinauto.findbestmatch import find_best_match ditto=Application().conn…

How to get the surface from a rect/line

I am trying to find the point where a line collides with a brick in the arkanoid that i am making. The most logical way i found is getting the mask from the line and use collidemask as it returns the p…