如何在Matplotlib中填充边框边界 [英] How to fill space to border with in Matplotlib

查看:668
本文介绍了如何在Matplotlib中填充边框边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在3张图之间填充空格,但我不知道如何限制图y2上的面积

I need to fill space between 3 graphs but I don't understand how to limit the area on the graph y2

import numpy as np
import matplotlib.pyplot as plt

y = lambda z: (4 * z - z ** 2) ** (1 / 2)
y1 = lambda x: (8 * x - x ** 2) ** (1 / 2)
y2 = lambda c: c * 3 ** (1 / 2)
x = np.linspace(0, 12, 100)
z = np.linspace(0, 12, 100)
c = np.linspace(0, 12, 100)
plt.ylim(0, 4)
plt.xlim(0, 4)

plt.plot(z, y(z), color='blue', label="y=(18-x^2)^(1/2)")
plt.plot(c, y2(c))
plt.plot(x, y1(x), color='red', label='y=3*2^(1/2) - (18-x^2)^(1/2)')

plt.grid(True, zorder=5)

plt.fill_between(x, y(z), y1(x), alpha=0.5)

plt.show()

推荐答案

要同时填充yy2上方的空间,可以同时使用两者中的最大值.为了仅填充y1y2上方的位置,您可以使用where参数:

To fill the space that is both above y and above y2, you can take the maximum of both. In order to only fill where y1 is above y2, you can you the where parameter:

plt.fill_between(x, np.maximum(y(z), y2(c)), y1(x), where=y2(c)<=y1(x), alpha=0.5)

您可能需要在linspace中使用100个以上的点,以避开较小的区域而不进行填充.对于此图像,我使用了np.linspace(0, 12, 500).

You might need to use more than 100 points in the linspaces to avoid small regions without filling. For this image I used np.linspace(0, 12, 500).

要获得更好的标签,您可以将其设置为乳胶格式(用$符号括起来,并在括号中添加大括号):

To have nicer labels, you could you latex format (enclose with $ signs, and add braces for the powers):

plt.plot(..., label="$y=(18-x^2)^{1/2}$")
plt.plot(..., label='$y=3*2^{1/2} - (18-x^2)^{1/2}$')

要获取平方根符号,请使用乳胶功能\sqrt.要在Python字符串中包含反斜杠,应将反斜杠加倍,或者在字符串前加上r(

To get a square root symbol, use the latex function \sqrt. To have a backslash in a Python string, either the backslash should be doubled, or the string should be preceded by an r (raw string).

plt.plot(..., label="$y=\\sqrt{18-x^2}$")
plt.plot(..., color='red', label='$y=3*\\sqrt{2} - \\sqrt{18-x^2}$')

这篇关于如何在Matplotlib中填充边框边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆