我正在尝试创建具有三种线条颜色的图表,并且只希望在图例中具有该颜色以及趋势线的标签。我进行了一些搜索,发现我应该可以将None放置在标签或'_nolegend_'上,但对我来说都不起作用。我还看到我可以在matplotlib中使用美术师来做到这一点,但实际上并不知道如何在for循环中创建这些美术师。感谢您的任何建议,因为此演示文稿即将推出。
for teacher in range(3):
teach = ['c','b','t']
for student in range(1,6):
std = teach[teacher] + str(student)
df_att_std = df_att[df_att['Student']==std]
print(df_att_std)
styles_lst=['s', '^', 'o', 'x', '*']
color_lst=['r', 'b', 'y']
style = styles_lst[student-1]
color = color_lst[teacher]
week = df_att_std['Week']
attitude = df_att_std['Attitude'] + teacher*.1
var = f'l_{std}'
if student == 1 and teacher == 0:
plt.plot(week, attitude, c=color, marker=style, label = "Cheryl", alpha=.85)
elif student == 1 and teacher == 1:
plt.plot(week, attitude, c=color, marker=style, label = "Brenda", alpha=.85)
elif student == 1 and teacher ==2:
plt.plot(week, attitude, c=color, marker=style, label = "Travis", alpha=.85)
else:
plt.plot(week, attitude, c=color, marker=style, label='_nolegend_', alpha=.85)
plt.plot(week, attitude, c=color, marker=style, alpha=.85)
# Trendline
x=df_att['Week']
y=df_att['Attitude']
z=numpy.polyfit(numpy.float32(x), numpy.float32(y), 1)
p=numpy.poly1d(z)
plt.plot(x,p(x), 'k--', linewidth=2)
yticks=['Somewhat Challenging', 'Neutral', 'Somewhat Positive',
'Positive']
plt.title("Teacher Student Relationship")
plt.xlabel('Week Number')
plt.ylabel('Attitude')
plt.yticks(ticks=[2,3,4,5], labels=yticks, rotation=30)
plt.xticks(ticks=[1,2,3,4,5])
plt.legend()
plt.show()
答案 0 :(得分:0)
错误是在if语句之外有一个图正在重新部署所有行。感谢ImportanceOfBeingEarnist的帮助。