如何在一个轴上绘制间隔

2024-04-25 00:22:36 发布

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

我是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]:
            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

desired output


Tags: rm代码forifdef绘制plt形式
2条回答

一个简单的循环就足够了。在

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

enter image description here

所以我不知道你为什么要用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()

这会让你

enter image description here

相关问题 更多 >