Я столкнулся с ошибкой при попытке отобразить легенду на графике Matplotlib. Мой код правильно генерирует 3D-график, но когда я пытаюсь отобразить легенду, я получаю следующую ошибку:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Definition of the concave function in two variables
def concave_function(x, y):
return -x**2 - y**2
# Definition of the partial derivative with respect to x
def partial_derivative_x(x, y):
return -2 * x
# Definition of the partial derivative with respect to y
def partial_derivative_y(x, y):
return -2 * y
# Definition of the tangent plane
def tangent_plane(x, y):
return z_0 + slope_x * (x - x_0) + slope_y * (y - y_0)
# Values for the vertical planes
y_0 = 1 # Section plane in y
x_0 = 2 # Section plane in x
z_0 = concave_function(x_0, y_0)
# Creation of points for the 3D plot
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = concave_function(X, Y)
# Calculation of the slope of the tangent at point (x0, y0) for the section y = y0
slope_x = partial_derivative_x(point1[0], y_0)
x_tangent = np.linspace(0, 2.5, 10)
z_tangent = z_point1 + slope_x * (x_tangent - point1[0])
# Calculation of the slope of the tangent at point (x0, y0) for the section x = x0
slope_y = partial_derivative_y(x_0, y_0)
y_tangent2 = np.linspace(-2, 2, 10)
z_tangent2 = z_point1 + slope_y * (y_tangent2 - point1[1])
# Tangent plane
Z_tangent = tangent_plane(X, Y)
# Creation of the sections of the function
Z_section_y = concave_function(x, y_0) # Function section on the plane y = y_0
Z_section_x = concave_function(x_0, y) # Function section on the plane x = x_0
# Calculation of points of interest
point1 = (x_0, y_0) # Point to calculate partial derivatives
point2 = (-1, y_0) # Point 2 on the section y = y_0
point3 = (0, y_0) # Point 3 on the section y = y_0
point4 = (x_0, -1) # Point 4 on the section x = x_0
point5 = (x_0, -2) # Point 5 on the section x = x_0
z_point1 = concave_function(point1[0], point1[1])
z_point2 = concave_function(point2[0], point2[1])
z_point3 = concave_function(point3[0], point3[1])
z_point4 = concave_function(point4[0], point4[1])
z_point5 = concave_function(point5[0], point5[1])
# Creation of the plane
def tangent_plane(x, y, x0, y0, z0, slope_x, slope_y):
return z0 + slope_x1 * (x - x0) + slope_y * (y - y0)
# Configuration of the 3D plot
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
# Plot of the concave function
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.6, edgecolor='none')
# Plot of the section of the function as a curve on the plane y = y_0
ax.plot(x, [y_0]*len(x), Z_section_y, color='red', linewidth=2, label=f'Section y = {y_0}')
# Adding the vertical plane for y = y_0
X_plane, Z_plane_y = np.meshgrid(x, np.linspace(np.min(Z), np.max(Z), 100))
Y_plane_y = np.full_like(X_plane, y_0)
ax.plot_surface(X_plane, Y_plane_y, Z_plane_y, color='blue', alpha=0.3)
# Plot of the section of the function as a curve on the plane x = x_0
ax.plot([x_0]*len(y), y, Z_section_x, color='green', linewidth=2, label=f'Section x = {x_0}')
# Adding the vertical plane for x = x_0
Y_plane_x, Z_plane_x = np.meshgrid(y, np.linspace(np.min(Z), np.max(Z), 100))
X_plane_x = np.full_like(Y_plane_x, x_0)
ax.plot_surface(X_plane_x, Y_plane_x, Z_plane_x, color='purple', alpha=0.3)
# Drawing the tangent line to the curve on the section y = y0 at point (x_0, y_0)
ax.plot(x_tangent, [y_0]*len(x_tangent), z_tangent, color='orange', linewidth=2, label="Tangent to the function on section y=y0 at (x0,y0)")
# Drawing the tangent line to the curve on the section x = x0 at point (x_0, y_0)
ax.plot([x_0]*len(y_tangent2), y_tangent2, z_tangent2, color='purple', linewidth=2, label="Tangent to the function on section x=x0 at (x0,y0)")
# Plot of the tangent plane
ax.plot_surface(X, Y, Z_tangent, color='cyan', alpha=0.5, label="Tangent Plane")
# Drawing the points used for secants
ax.scatter([point1[0], point2[0]], [y_0, y_0], [z_point1, z_point2], color='black', s=50)
# Labels and title
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)')
# Set the viewing angle
ax.view_init(elev=30, azim=45)
# Show the legend outside the plot
ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.show()
Хотя график отображается правильно, я не понимаю, почему возникает эта ошибка. Может ли кто-нибудь объяснить, что может быть причиной этой проблемы и как ее решить?
Спасибо!
Я столкнулся с ошибкой при попытке отобразить легенду на графике Matplotlib. Мой код правильно генерирует 3D-график, но когда я пытаюсь отобразить легенду, я получаю следующую ошибку: [code]File ~\anaconda3\Lib\site-packages\matplotlib\legend_handler.py:783, in HandlerPolyCollection._update_prop..first_color(colors) 782 def first_color(colors): --> 783 if colors.size == 0: 784 return (0, 0, 0, 0) 785 return tuple(colors[0])
AttributeError: 'tuple' object has no attribute 'size' [/code] Вот соответствующая часть моего кода: [code]import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D
# Definition of the concave function in two variables def concave_function(x, y): return -x**2 - y**2
# Definition of the partial derivative with respect to x def partial_derivative_x(x, y): return -2 * x
# Definition of the partial derivative with respect to y def partial_derivative_y(x, y): return -2 * y
# Values for the vertical planes y_0 = 1 # Section plane in y x_0 = 2 # Section plane in x z_0 = concave_function(x_0, y_0)
# Creation of points for the 3D plot x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = concave_function(X, Y)
# Calculation of the slope of the tangent at point (x0, y0) for the section y = y0 slope_x = partial_derivative_x(point1[0], y_0) x_tangent = np.linspace(0, 2.5, 10) z_tangent = z_point1 + slope_x * (x_tangent - point1[0])
# Calculation of the slope of the tangent at point (x0, y0) for the section x = x0 slope_y = partial_derivative_y(x_0, y_0) y_tangent2 = np.linspace(-2, 2, 10) z_tangent2 = z_point1 + slope_y * (y_tangent2 - point1[1])
# Tangent plane Z_tangent = tangent_plane(X, Y)
# Creation of the sections of the function Z_section_y = concave_function(x, y_0) # Function section on the plane y = y_0 Z_section_x = concave_function(x_0, y) # Function section on the plane x = x_0
# Calculation of points of interest point1 = (x_0, y_0) # Point to calculate partial derivatives point2 = (-1, y_0) # Point 2 on the section y = y_0 point3 = (0, y_0) # Point 3 on the section y = y_0 point4 = (x_0, -1) # Point 4 on the section x = x_0 point5 = (x_0, -2) # Point 5 on the section x = x_0
# Creation of the plane def tangent_plane(x, y, x0, y0, z0, slope_x, slope_y): return z0 + slope_x1 * (x - x0) + slope_y * (y - y0)
# Configuration of the 3D plot fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d')
# Plot of the concave function ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.6, edgecolor='none')
# Plot of the section of the function as a curve on the plane y = y_0 ax.plot(x, [y_0]*len(x), Z_section_y, color='red', linewidth=2, label=f'Section y = {y_0}')
# Adding the vertical plane for y = y_0 X_plane, Z_plane_y = np.meshgrid(x, np.linspace(np.min(Z), np.max(Z), 100)) Y_plane_y = np.full_like(X_plane, y_0) ax.plot_surface(X_plane, Y_plane_y, Z_plane_y, color='blue', alpha=0.3)
# Plot of the section of the function as a curve on the plane x = x_0 ax.plot([x_0]*len(y), y, Z_section_x, color='green', linewidth=2, label=f'Section x = {x_0}')
# Adding the vertical plane for x = x_0 Y_plane_x, Z_plane_x = np.meshgrid(y, np.linspace(np.min(Z), np.max(Z), 100)) X_plane_x = np.full_like(Y_plane_x, x_0) ax.plot_surface(X_plane_x, Y_plane_x, Z_plane_x, color='purple', alpha=0.3)
# Drawing the tangent line to the curve on the section y = y0 at point (x_0, y_0) ax.plot(x_tangent, [y_0]*len(x_tangent), z_tangent, color='orange', linewidth=2, label="Tangent to the function on section y=y0 at (x0,y0)") # Drawing the tangent line to the curve on the section x = x0 at point (x_0, y_0) ax.plot([x_0]*len(y_tangent2), y_tangent2, z_tangent2, color='purple', linewidth=2, label="Tangent to the function on section x=x0 at (x0,y0)")
# Plot of the tangent plane ax.plot_surface(X, Y, Z_tangent, color='cyan', alpha=0.5, label="Tangent Plane")
# Drawing the points used for secants ax.scatter([point1[0], point2[0]], [y_0, y_0], [z_point1, z_point2], color='black', s=50)
# Labels and title ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('f(x, y)')
# Set the viewing angle ax.view_init(elev=30, azim=45)
# Show the legend outside the plot ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.show() [/code] Хотя график отображается правильно, я не понимаю, почему возникает эта ошибка. Может ли кто-нибудь объяснить, что может быть причиной этой проблемы и как ее решить? Спасибо!
Я столкнулся с ошибкой при попытке отобразить легенду на графике Matplotlib. Мой код правильно генерирует 3D-график, но когда я пытаюсь отобразить легенду, я получаю следующую ошибку:
File...
У меня есть несколько классов и их отношения вот так
class Account(db.Model, UserMixin):
id = Column(Integer, primary_key=True)
user_name = Column(db.String(50), nullable=False, unique=True)
password = Column(String(50), nullable=False)
create_day...
У меня есть код:
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import...
У меня есть 2 класса и их отношения такие
class User(db.Model):
id = Column(Integer, primary_key=True)
last_name = Column(String(50), nullable=False)
first_name = Column(String(50), nullable=False)
gender = Column(String(50))
birth_day =...
Я на федоре 41, с виртуальным набором с Python 3.12.7 (matplotlib == 3.9.2). Следующий код:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 7))
или только
import gi
gi.require_version( Gtk , 4.0 )