简体   繁体   中英

Strange Behavior of Python's Matplotlib Module - Plotting a Circle

I am currently writing a program which must generate a set of plots. EACH plot must have 3 concentric circles on it whose radii are determined by a data set. Further, another red colored circle must also be added which can have a different centre. However, I ran into various problems. Unless the radius of the circle/s is/are too large, I should see 3 black and 1 red circle on the plot but I don't.

I isolated the piece of code that makes the plot and here it is -

import matplotlib.pyplot as plt

fig1 = plt.figure(1, figsize=(6,6))
plt.xlim(-30,30)
plt.ylim(-30,30)

rcircle1 = plt.Circle( (0,0), 6.0, edgecolor="black", facecolor="white")
rcircle2 = plt.Circle( (0,0), 12.0, edgecolor="black", facecolor="white")
rcircle3 = plt.Circle( (0,0), 18.0, edgecolor="black", facecolor="white")
bcircle = plt.Circle( (8.5,-5.8)  ,2,  edgecolor="red", facecolor="white")

ax = fig1.gca()
ax.add_artist(rcircle1)
ax.add_artist(rcircle2)
ax.add_artist(rcircle3)
ax.add_artist(bcircle)

fig1.savefig("Model.png", dpi=150)

The output for above is -

输出上述代码。

I tried looking into various Class variables associated with Circle() and add_artist() but unable to find something that might be affecting this behavior.

My current work around is the following code -

import numpy as np
import matplotlib.pyplot as plt

th = np.arange(-3.14,3.14,0.01)

fig1 = plt.figure(1,figsize=(6,6))
plt.xlim(-30,30)
plt.ylim(-30,30)

plt.plot( 6*np.cos(th), 6*np.sin(th), color="black")
plt.plot( 12*np.cos(th), 12*np.sin(th), color="black")
plt.plot( 18*np.cos(th), 18*np.sin(th), color="black")
# (8,5, -5,8)
plt.plot( 2*np.cos(th) + 8.5, 2*np.sin(th) - 5.8, color="red")

fig1.savefig("Hard.png", dpi=150)

The output generated by the above code is exactly what I want to be!

在此输入图像描述

While this does work, it defeats the purpose of having Circle() like methods in matplotlib. Can anyone comment why the first code is not working as I expect it to be?

Your problem is the facecolor argument. You're adding the biggest circle last, and it has an opaque center.

In the second example you're plotting a line, not a "filled" circle.

Either change the order you add the circles in (or supply a zorder kwarg), or pass in facecolor='none' (Note: it's the string "none" , not the object None ) to get an "unfilled" circle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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