首页 > 解决方案 > 如何在带有文字的图形中绘制虚线?

问题描述

我已经使用 matplotlib 绘制了一个图表。我想在某些地方用写在上面的文字平行于图中的 y 轴制作直线。有人知道该怎么做吗?查看图像以获得更清晰的信息:

所需图表

该图像具有我想要绘制的所需虚线。我想像在图像中一样为“请假决定”画线,垂直线平行于 y 轴,上面写有请假决定。

例如代码:

    import matplotlib.pyplot as plt

r=[70,70,70,70]
e=[0,0,0,0]
r_0=[70]
r_1=[70]
r_2=[70]
r_3=[70]

for i in range(5):
    r[0]=r[0]*0.9
    r_0.append(r[0])
    e[0]=e[0]+1
    
   
    
    if r[1]<=200 :
        r[1]=r[1]+4
        r_1.append(r[1])
        
    
    if r[2]<=200 :
        r_2.append(r[2])
        r[2]=r[2]+8
               
    
    if r[3]<=200 :
        r_3.append(r[3])
        r[3]=r[3]+16
    
    
for i in range(5):
    r[1]=r[1]*0.9
    r_1.append(r[1])
    e[1]=e[1]+1
    
    
    
    if r[0]<=200 :
        r[0]=r[0]+2
        r_0.append(r[0])
        
    
    if r[2]<=200 :
        r[2]=r[2]+8
        r_2.append(r[2])
 
        
   
    if r[3]<=200 :
        r[3]=r[3]+16
        r_3.append(r[3])
    else:
       r_3.append(214)
 

for i in range(5):
    r[2]=r[2]*0.9
    r_2.append(r[2])
    e[2]=e[2]+1
    
    
   
    if r[0]<=200 :
        r[0]=r[0]+2
        r_0.append(r[0])
        
   
    if r[1]<=200 :
        r[1]=r[1]+4
        r_1.append(r[1])
        
    
    if r[3]<=200 :
        r[3]=r[3]+16
        r_3.append(r[3])

    else:
         r_3.append(214)   
    

for i in range(5):
    r[3]=r[3]*0.9
    r_3.append(r[3])
    e[3]=e[3]+1
       
    
    if r[0]<=200 :
        r[0]=r[0]+2
        r_0.append(r[0])
    
    
    if r[2]<=200 :
        r[2]=r[2]+8
        r_2.append(r[2])
        
   
    if r[1]<=200 :
        r[1]=r[1]+4
        r_1.append(r[1])

   
x=range(21)
xb, r_0b = x[1:6], r_0[1:6]
plt.plot(x,r_0,'--')
plt.plot(xb, r_0b, 'tab:blue', marker='D')

x=range(21)
xb, r_1b = x[6:11], r_1[6:11]
plt.plot(x,r_1,'--')
plt.plot(xb, r_1b, 'tab:orange', marker='D')

x=range(21)
xb, r_2b = x[11:16], r_2[11:16]
plt.plot(x,r_2,'--')
plt.plot(xb, r_2b, 'tab:green', marker='D')

x=range(21)
xb, r_3b = x[16:21], r_3[16:21]
plt.plot(x,r_3,'--')
plt.ylim(0,250)
plt.xlabel("Time")
plt.ylabel("Reward")
plt.title("Reward_Dynamics_B_3")
plt.plot(xb, r_3b, 'tab:red', marker='D')

我的代码输出: 在此处输入图像描述

标签: pythonpython-3.xmatplotlibgraphdotted-line

解决方案


您可以在之前添加这些plt.show()

xpos = 2.5 #x-value of the vertical line
text = "hello" #text you wanna add to the verical line

plt.vlines(x=xpos, ymin=0, ymax=250, color = 'black', linestyles="dashed")
plt.text(x=xpos, y=125, s=text, ha='center', va='center',rotation='vertical', backgroundcolor='white'))

产生:

在此处输入图像描述


推荐阅读