如何在同一情节中画虚线和粗线

2024-04-19 23:25:27 发布

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

我有一个列表,我想以这样一种方式绘制列表,对于x轴的特定范围,线是虚线,而对于其他范围,它是实线。 e、 g:

y=[11,22,33,44,55,66,77,88,99,100]
x=[1,2,3,4,5,6,7,8,9,10]

我这样做:

if i range(4,8):
   plt.plot(x,y,marker='D')
else :
   plt.plot(x,y,'--')
plt.show()

但这是行不通的

有人能帮忙吗


3条回答

将数据分为3个区间

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting

x = [1,2,3,4,5,6,7,8,9,10]
y = [11,22,33,44,55,66,77,88,99,100]
fig, ax = plt.subplots()

m, n = 4, 8

x1, x2, x3 = x[:m+1], x[m:n+1], x[n:]
y1, y2, y3 = y[:m+1], y[m:n+1], y[n:]

ax.plot(x1, y1, color='red', linestyle='solid', marker='D')
ax.plot(x2, y2, color='blue', linestyle='dashed')
ax.plot(x3, y3, color='red', linestyle='solid', marker='D')


plt.show()

根据x的值更改线特征:

import numpy as np
from matplotlib import pyplot as plt
  • 制作列表的数组

     y = np.array([11,22,33,44,55,66,77,88,99,100])
     x = np.array([1,2,3,4,5,6,7,8,9,10])
    
  • 根据您的条件生成布尔数组

     dashed = np.logical_or(x<4,x>=8)
    
  • 打印时,使用布尔数组过滤数据

     plt.plot(x[~dashed],y[~dashed],color='blue',marker='D')
     plt.plot(x[dashed],y[dashed],color='blue',ls=' ')
    

这是一个全系列颜色相同的解决方案:

import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9,10]
y = [11,22,33,44,55,66,77,88,99,100]
fig, ax = plt.subplots()

x1, y1 = x[:4], y[:4]
x2, y2 = x[3:8], y[3:8]
x3, y3 = x[7:], y[7:]

ax.plot(x1, y1, marker='D', color='b')
ax.plot(x2, y2, ' ', color='b')
ax.plot(x3, y3, marker='D', color='b')

相关问题 更多 >