【问题标题】:Plot legend faded, how do I fix this? [duplicate]剧情传说消失了,我该如何解决? [复制]
【发布时间】:2021-10-18 14:19:06
【问题描述】:

我一直在尝试为我的情节获取图例,但是图例上的颜色确实褪色了,因此很难看出哪条线是哪条线,有人知道如何解决这个问题吗?

这是代码,以防有人想看。

谢谢

import pandas as pd
import glob 
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks

path = r'C:\Users\benjy\impedance_measurements'
all_files = glob.glob(path +"/*.csv")

print(len(all_files)/10)
data = np.ndarray((8, 200000))
x_axis = range(100, 20000100, 100)

for i in range(0,8):

    dataset = np.ndarray((10, 200000))

    for j in range(10):

        df = pd.read_csv(all_files[10*i + j], skiprows=8, usecols=[3])
        # this line needed as otherwise cannot put into row of an array 
        df_num = df.values.ravel()
        dataset[j,:] = df_num[0:200000]
        

    mean = np.mean(dataset, axis=0)
    data[i,:] = mean

plt.plot(x_axis, data[0], label='steps 1 and 5 cemented', linewidth=0.2 )
plt.plot(x_axis, data[1], label='steps 1 and 5 cementless', linewidth=0.2)
plt.plot(x_axis, data[2], label='step 1 cemented & 5 cementless',  linewidth=0.2)
plt.plot(x_axis, data[3], label='step 1 cemented', linewidth=0.2)
plt.plot(x_axis, data[4], label='step 1 cementless & 5 cemented', linewidth=0.2)
plt.plot(x_axis, data[5], label='step 1 cementless', linewidth=0.2)
plt.plot(x_axis, data[6], label='step 5 cemented', linewidth=0.2)
plt.plot(x_axis, data[7], label='step 5 cementeless', linewidth=0.2)

plt.legend()
plt.show()

【问题讨论】:

  • 是不是受线宽影响,还是不能通过设置linewidth=1来改善?
  • 这行得通,但是有没有办法保持线宽细并且有清晰的图例,信号很嘈杂,所以当它们很细时我更容易观察到?
  • 单独制作一个图例怎么样?
  • 你是什么意思?通过将所有标签放在 plt.legend()

标签: python pandas matplotlib plot data-visualization


【解决方案1】:

这是制作独立于情节的图例的方法:

fig, ax = plt.subplots()
label = ['steps 1 and 5 cemented','steps 1 and 5 cementless','step 1 cemented & 5 cementless','step 1 cemented','step 1 cementless & 5 cemented','step 1 cementless','step 5 cemented','step 5 cementeless']
color = ['tab:blue','tab:orange','tab:green','tab:red','tab:purple','tab:brown','tab:pink','tab:gray']
handles = [Line2D([0], [0], marker='', color=color[i]) for i in range(len(color))]
plt.legend(handles, label)

输出:

【讨论】:

    【解决方案2】:

    您可以单独编辑图例中线条的线宽(不影响绘图):

    for legobj in leg.legendHandles:
        legobj.set_linewidth(4)
    

    完整代码

    import matplotlib.pyplot as plt
    import numpy as np
    
    N = 10000
    x = np.linspace(0, 10, N)
    y1 = np.sqrt(x) + 1/10*np.random.randn(N)
    y2 = np.exp(-x) + 1/10*np.random.randn(N)
    
    
    fig, ax = plt.subplots()
    
    ax.plot(x, y1, label = 'signal 1', linewidth = 0.2)
    ax.plot(x, y2, label = 'signal 2', linewidth = 0.2)
    
    leg = ax.legend(frameon = True)
    
    for legobj in leg.legendHandles:
        legobj.set_linewidth(4)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 2014-09-03
      • 1970-01-01
      • 2021-12-28
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多