简体   繁体   中英

Superimpose 2 plots in matplotlib - empty plot

I am trying to plot a circle and a rectangle on the same graph with matplotlib.

Instead, I get an empty plot. What should I do?

Here is my code:

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 

plt.axes()
circle = plt.Circle((0, 0), radius=0.75, fc='y')
plt.axis('scaled')
rectangle = plt.Rectangle((10, 10), 100, 100, fc='r')
plt.gca().add_patch(rectangle)

you need to set the axes limits. You can do this with plt.autoscale() , or plt.xlim and plt.ylim . You also need to add the circle patch. Add these lines at the end of your script:

plt.gca().add_patch(circle)
plt.autoscale()

在此处输入图片说明

Your code is mostly working. The only issue is

plt.axis('scaled')

Double check your axis limits - this line only works with normal plot objects, not patches, so if you remove this line you should see the rectangle (though you also forgot to add the circle in your pasted code), as long you you update the axis limits (I used plt.axis([-1, 120, -1, 120]) below to achieve this).

A full working listing is:

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 

plt.axes()
circle = plt.Circle((0, 0), radius=0.75, fc='y')
plt.gca().add_patch(circle)
rectangle = plt.Rectangle((10, 10), 100, 100, fc='r')
plt.gca().add_patch(rectangle)
plt.axis([-1, 120, -1, 120])

Alternatively, plt.autoscale also works to set the data limits as suggested by tom.

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