python-3.x - 在 matplotlib 中缩小图形?
问题描述
我是 python 和 matplotlib 的新手。我正在从该站点查看以下给定示例: https://glowingpython.blogspot.com/2012/01/how-to-plot-two-variable-functions-with.html 因为我希望找到给定的最佳准确性我的模型的学习率和纪元数。但是当我稍微玩一下它时,它会缩小到一个小尺寸的图表。我怎样才能让它保持它的大小?示例和我的更改如下。
这个例子:
from numpy import exp, arange
from pylab import meshgrid, cm, imshow, contour, clabel, colorbar, axis, title, show
# the function that I'm going to plot
def z_func(x, y):
return (1 - (x ** 2 + y ** 3)) * exp(-(x ** 2 + y ** 2) / 2)
x = arange(-3.0, 3.0, 0.1)
y = arange(-3.0, 3.0, 0.1)
X, Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
im = imshow(Z, cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z, arange(-1, 1.5, 0.2), linewidths=2, cmap=cm.Set2)
clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('$z=(1-x^2+y^3) e^{-(x^2+y^2)/2}$')
show()
我的改变:
from numpy import exp, arange
from pylab import meshgrid, cm, imshow, contour, clabel, colorbar, axis, title, show
import random
# the function that I'm going to plot
def z_func(x, y):
return (x * y * random.random())
x = arange(0.001, 1.001, 0.001)
y = arange(1.0, 101.0, 1.0)
X, Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
im = imshow(Z, cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z, arange(-1, 1.5, 0.2), linewidths=2, cmap=cm.Set2)
clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('title')
show()
解决方案
与官方示例不同,由于 x 轴和 y 轴的范围不同,它会缩小。要获得正方形imshow
,您需要调整纵横比。这可以按如下方式完成,如下所示
import numpy as np
import matplotlib.pyplot as plt
import random
def z_func(x, y):
return (x * y * random.random())
x = np.arange(0.001, 1.001, 0.001)
y = np.arange(1.0, 101.0, 1.0)
X, Y = np.meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
# Compute aspect ratio
dx = (x.max()-x.min()) / X.shape[0]
dy = (y.max()-y.min()) / X.shape[1]
dx_dy = dy/dx
im = plt.imshow(Z, cmap=cm.RdBu, aspect=dx_dy) # drawing the function
cset = plt.contour(Z, np.arange(-1, 1.5, 0.2), linewidths=2, cmap=cm.Set2)
plt.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
plt.colorbar(im) # adding the colobar on the right
plt.title('title')
plt.show()
推荐阅读
- powershell - 当我向我的对象添加新列时,即使我的值相等也会出错?
- git - 在 CloudRun 上使用 git2go 克隆
- java - 根据属性值返回过滤后的 java 对象列表
- java - 在 Jenkins 上部署 Spring Boot 应用程序
- java - 如何将读取和强制转换为 char 数组
- django - django频道redis关闭时间过长被杀
- ms-access - SSIS 脚本任务打开 MS Access 运行宏
- ios - Swift:无论用户单击哪个按钮操作,都会显示请求审核
- azure - Azure B2C 自定义属性固定长度
- java - 通过 Java 中的 FileOutputStream 写入的文件没有被 python 使用 AudioSegment.from_file 访问