Python 如何在一个轴上绘制间隔
我是python新手,我试图以区间的形式在一个轴x上绘制一些x,y对。例如,如果我有下面的2,3,2,4,4,4,1,3对,我应该在下面的图片中生成图形 我尝试了这个代码,但它没有给我正确的结果Python 如何在一个轴上绘制间隔,python,matplotlib,Python,Matplotlib,我是python新手,我试图以区间的形式在一个轴x上绘制一些x,y对。例如,如果我有下面的2,3,2,4,4,4,1,3对,我应该在下面的图片中生成图形 我尝试了这个代码,但它没有给我正确的结果 def DrawGraph (RM): for i in range(0,RM.shape[0]-1): c1=lastOne2(RM,i) ax1=plt.subplot(1,1,1) if c1[0] == c1[1]:
def DrawGraph (RM):
for i in range(0,RM.shape[0]-1):
c1=lastOne2(RM,i)
ax1=plt.subplot(1,1,1)
if c1[0] == c1[1]:
plt.plot(c1[0],c1[1],'ro')
if c1[0] < c1[1]:
ax1.barh(c1[0], c1[1], height=0.05)
if c1[0] > c1[1]:
ax1.barh(c1[1], c1[0], height=0.05)
return plt
所以我不知道你为什么要用barh。我认为只使用法线并创建一些y值要简单得多。除此之外,这会让你得到你想要的。请注意,您可以通过kwargs指定plt.plot的任何关键字参数。此外,deltaY还可以调整水平线之间的距离
# Import
import matplotlib.pyplot as plt
import numpy as np
def DrawGraph(RM,deltaY=1,**kwargs):
# Create figure
ax=plt.subplot(1,1,1)
for i in range(0,RM.shape[0]):
# Grab current interval
c1=RM[i]
# Create y-values and shift intervals up by (i+1)*deltaY
y=(i+1)*deltaY*np.ones((2,1))
# Draw
if c1[0] == c1[1]:
ax.plot([c1[0]],[i*deltaY],'o',**kwargs)
if c1[0] < c1[1]:
ax.plot(c1,y,**kwargs)
if c1[0] > c1[1]:
ax.plot(c1,y,lw=lw,**kwargs)
# Set ylim so it looks nice
ax.set_ylim([0,deltaY*(i+2)])
return ax
# Define intervals
intervals=np.array([(2,3),(2,4),(4,4),(1,3)])
# Plot
DrawGraph(intervals,lw=5,c='b')
# Draw
plt.show()
这会让你
一个简单的循环就足够了
import matplotlib.pyplot as plt
import numpy as np
p = [(2,3),(2,4),(4,4),(1,3)]
def drawp(p, dy=1,**kw):
for i,x in enumerate(p):
plt.plot(np.unique(x),[i*dy]*len(np.unique(x)),
marker="s"*(2-len(np.unique(x))), ms=kw.get("lw",2),**kw)
drawp(p, color="crimson")
plt.show()
你试过自己写一些代码吗?如果是的话,请发布你到目前为止所拥有的。我编辑了它,谢谢你的帮助