如何用matplotlib在双y轴图中绘制圆?

时间:2018-01-27 15:45:06

标签: python matplotlib

我是matplotlib的新手。我试图绘制一个空圆圈来指定双y轴图中的数据点。我用plt.Cirle来做这项工作。但它没有用。你能帮助我吗?这是代码,我得到的是一个矩形而不是一个圆圈。

from matplotlib.patches import *


fig = plt.figure()
ax1 = plt.gca()
markers,stems,base = ax1.stem(x1,oscillator,linefmt='k-',markerfmt='ko')
for stem in stems:
    stem.set_linewidth(1)
ax1.set_ylim(0,0.4)
ax1.set_xlim(250,500)
ax1.set_xlabel('Wavelength (nm)')
ax1.set_ylabel('Oscillator strength')
ax1.annotate('Oscillator strength', xy=(307,0.31), xytext=(325,0.35),
            arrowprops=dict(arrowstyle= '-|>',connectionstyle='arc3,rad=0.5',lw = 1, color ='k'))
circ = plt.Circle((300,0.3), radius=20, edgecolor='g')
ax1.add_artist(circ)


ax2 = ax1.twinx()
ax2.plot(x2,absorbance,'r-',linewidth=1)
ax2.spines['right'].set_color('red')
ax2.tick_params(axis='y', colors='red')
ax2.yaxis.label.set_color('red')
ax2.set_ylabel('Absorbance',color='r')
ax2.annotate('', xy=(414,0.31), xytext=(450,0.33),
            arrowprops=dict(arrowstyle= '-|>',connectionstyle='arc3,rad=0.5',lw = 1, color ='r'))
ax2.text(450,0.33,'Absorbance',color='red')

plt.show()

这是图表,蓝色矩形应该是一个圆圈:

Here is the graph, the blue rectangle should be a circle

2 个答案:

答案 0 :(得分:0)

问题是您在非常不相等的数据限制的轴上创建一个圆。虽然x轴的范围在数百个范围内,但y轴的范围在低于1的范围内。因此,您观察到的矩形是一个非常扭曲的圆。

enter image description here

对于此类情况,如果限制明显不同,或者在任何情况下您希望在屏幕上显示真圆,则应在显示坐标中以轴坐标或更好的方式定义圆。

在显示坐标中生成圆的简单方法是散点图。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(303,320,3)
y = np.array([.25,.13,.09,.33,.16,.11])

fig, ax = plt.subplots()
ax.stem(x,y,linefmt='k-',markerfmt='ko')

ax.scatter([x[3]],[y[3]], s=40**2, edgecolor="green", facecolor="None", linewidth=3 )
ax.axis([250,500,0,.4])

plt.show()

enter image description here

答案 1 :(得分:-2)

这可以解决您的问题:

https://matplotlib.org/gallery/api/patch_collection.html

from matplotlib.patches import Circle, Wedge
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

patches = []

circle = Circle((0.5, 0.8), 0.25) #Filled circle
patches.append(circle)

patches += [
Wedge((.3, .7), .1, 0, 360),             # Full circle
Wedge((.7, .8), .2, 0, 360, width=0.05),  # Full ring
Wedge((.8, .3), .2, 0, 45),              # Full sector
Wedge((.8, .3), .2, 45, 90, width=0.10)] # Ring sector

p = PatchCollection(patches, alpha=0.4)
ax.add_collection(p)

plt.show()