plotting single 3D point on top of plot_surface in python matplotlib

2024/9/22 20:45:44

I have some code to plot 3D surfaces in Python using matplotlib:

import math import numpy as np
import matplotlib.pyplot as plt
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import seaborn as sns
sns.set(style="white")def surface_map(func, xmin=0, xmax=1, ymin=0, ymax=1, step_size=0.05, maxz=25000):X, Y = meshgrid(np.arange(xmin, xmax, step_size),np.arange(ymin, ymax, step_size))Z = np.zeros(X.shape)for i in range(X.shape[0]):for j in range(X.shape[1]):Z[i, j] = min(func(X[i, j], Y[i, j]), maxz)return X, Y, Zdef plot_surface(X, Y, Z, xlabel, ylabel, zlabel, title, point=None, size=25):fig = plt.figure()ax = fig.gca(projection='3d')surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, vmin=0, vmax=20*1000,cmap=cm.RdBu, linewidth=0, antialiased=True)ax.zaxis.set_major_locator(LinearLocator(10))ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))ax.set_xlabel(xlabel)ax.set_ylabel(ylabel)ax.set_zlabel(zlabel)ax.set_title(title)fig.colorbar(surf, shrink=0.5, aspect=5)if point:ax.hold(True)func, fpr, recall = pointax.scatter([fpr], [recall], [func(fpr, recall)], s=size, c='b', marker='.', zorder=10)plt.show()

And then I call it like so:

# create mesh 
R, FPR, FuncValue = surface_map(my_function, xmin=0, xmax=1, ymin=0, ymax=1, step_size=0.05, maxz=20*1000)# plot it
plot_surface(R, FPR, FuncValue, xlabel="Recall", ylabel="FPR", zlabel="Function Value", title="Recall Settings Payout Function",point=(my_function, 0.5, 0.5))

I'm setting ax.scatter to use large marker sizes and a high zorder, but no point gets drawn on the surface when the plot gets rendered.

What am I missing?

Answer

The point you are looking for is there, but hidden "inside" the surface. This is a common problem in matplotlib.

I see two options here:

  1. Make the surface plot semitransparent, i.e. use alpha=.8 or similar.
  2. Use plot instead of scatter.
https://en.xdnf.cn/q/71800.html

Related Q&A

python group/user management packages

I was looking for python user/group management package.(Creation of user group and adding/removing members to that group) I found flask_dashed. https://github.com/jeanphix/Flask-Dashed/ It more or less…

Resize NumPy array to smaller size without copy

When I shrink a numpy array using the resize method (i.e. the array gets smaller due to the resize), is it guaranteed that no copy is made?Example:a = np.arange(10) # array([0, 1, 2, 3, 4, …

TensorFlow FileWriter not writing to file

I am training a simple TensorFlow model. The training aspect works fine, but no logs are being written to /tmp/tensorflow_logs and Im not sure why. Could anyone provide some insight? Thank you# import…

python time.strftime %z is always zero instead of timezone offset

>>> import time >>> t=1440935442 >>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.gmtime(t)) 2015/08/30-11:50:42 +0000 >>> time.strftime("%Y/%m/%d-%H:%M:…

Python: Nested for loops or next statement

Im a rookie hobbyist and I nest for loops when I write python, like so:dict = {key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1}}for key in dict:for subkey/value in key:do it to itIm a…

How to install cython an Anaconda 64 bits with Windows 10?

Its all in the title, does someone have a step by step method to install cython and run it on Anaconda 64 bits on Windows 10? I search for hours and there are a lot of tutorials... For things that I w…

Using DictWriter to write a CSV when the fields are not known beforehand

I am parsing a large piece of text into dictionaries, with the end objective of creating a CSV file with the keys as column headers. csv.DictWriter(csvfile, fieldnames, restval=, extrasaction=raise, di…

How to Save io.BytesIO pdfrw PDF into Django FileField

What I am trying to do is basically:Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file, name="Some n…

Which python static checker can catch forgotten await problems?

Code: from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print(agen start)yield 1yield 2async def agenmaker() -> AsyncIterable[str]:print(agenmaker start)return …

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…