如何用matplotlib在双y轴图形中画圆?

2024-05-29 11:52:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉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


Tags: matplotlibpltredstrengthcolor矩形setoscillator
2条回答

问题是你在一个数据限制非常不相等的轴上创建一个圆。当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

这样可以解决您的问题:

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()

相关问题 更多 >

    热门问题