【问题标题】:How to make dotted and bold lines in the same plot如何在同一情节中制作虚线和粗线
【发布时间】:2021-09-22 19:07:05
【问题描述】:

我有一个列表,我想以这样的方式绘制列表:对于 x 轴的某些范围,线条是虚线,而对于其他范围,它是实心的。 例如:

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

但这不起作用。

有人可以帮忙吗?

【问题讨论】:

  • 我认为这个情节和代码将回答 OP:plot
  • @TrentonMcKinney 是的,但颜色与蓝色相同。表明它是同一行。
  • plt.plot(xb, yb, 'tab:blue', marker='D')

标签: python python-3.x matplotlib plot graph


【解决方案1】:

将数据分成 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()

【讨论】:

    【解决方案2】:

    以下是整行颜色相同的解决方案:

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

    【讨论】:

      【解决方案3】:

      根据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='--')
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 1970-01-01
        • 2021-08-19
        • 2016-03-11
        相关资源
        最近更新 更多