繁体   English   中英

Matplotlib半黑半白圈

[英]Matplotlib half black and half white circle

我想在matplotlib图的原点放置一个半黑半半的白色圆圈。 我知道存在一个Circle类 ,但我不知道如何指定圆的左半部分应该是白色而右半部分应该是黑色的。 (一个理想的解决方案可以让我指定圆的方向 - 例如我应该能够旋转它,以便例如顶部可以是白色而底部是黑色)。

最简单的方法是使用两个Wedge (这不会自动重新缩放轴,但如果您愿意,可以轻松添加。)

作为一个简单的例子:

import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

def main():
    fig, ax = plt.subplots()
    dual_half_circle((0.5, 0.5), radius=0.3, angle=90, ax=ax)
    ax.axis('equal')
    plt.show()

def dual_half_circle(center, radius, angle=0, ax=None, colors=('w','k'),
                     **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) with the 
    specified facecolors *colors* rotated at *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

main()

在此输入图像描述

如果您希望它始终位于原点,您可以将变换指定为ax.transAxes ,并关闭剪裁。

例如

import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

def main():
    fig, ax = plt.subplots()
    dual_half_circle(radius=0.1, angle=90, ax=ax)
    ax.axis('equal')
    plt.show()

def dual_half_circle(radius, angle=0, ax=None, colors=('w','k'), **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) at the lower
    left corner of the axes with the specified facecolors *colors* rotated at
    *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    kwargs.update(transform=ax.transAxes, clip_on=False)
    center = (0, 0)
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

main()

但是,这将使圆的“圆度”取决于轴的轮廓的纵横比。 (你可以通过几种方式解决这个问题,但它会变得更加复杂。请告诉我这是你的想法,我可以展示一个更详细的例子。)我也可能误解了你的意思“在原点”。

如果您的字体带有此符号,则可以使用unicode半满圆(U + 25D0)。 奇怪的是,这不是在STIX(包含在matplotlib中),但我知道它在DejaVu Sans中,所以我将从那里使用它。

在此输入图像描述

import matplotlib.pyplot as plt
import matplotlib.font_manager
from numpy import *

path = '/full/path/to/font/DejaVuSans.ttf'
f0 = matplotlib.font_manager.FontProperties()    
f0.set_file(path)

plt.figure()
plt.xlim(-1.2,1.2)
plt.ylim(-1.2,1.2)

for angle in arange(0, 2*pi, 2*pi/10):
    x, y = cos(angle), sin(angle)
    plt.text(x, y, u'\u25D0', fontproperties=f0, rotation=angle*(180/pi), size=30)

plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM