python - 如何使最后绘制的 line2D 始终保持相同的颜色?
问题描述
我正在编写一个程序,用户可以在定义的轴上绘制函数。有什么办法可以使最后绘制的函数始终是固定颜色(比如说绿色)?
例如,下面的代码将多项式的次数作为输入,并绘制所有相同和更低次数的多项式。我想要一个调整,比如最后一个图(在这种情况下是最高次数的多项式)总是绿色的:
import numpy as np
import matplotlib.pyplot as plt
def plot_polynomials(highest_degree):
x = np.arange(0,1,0.01)
for degree in np.arange(1,highest_degree+1):
coefficients = np.repeat(1,degree)
label = 'degree={}'.format(degree)
polynomial = np.polynomial.polynomial.polyval(x, coefficients)
plt.plot(x, polynomial, label=label)
plt.legend()
plt.show()
plot_polynomials(6)
期待评论!
解决方案
这应该这样做:
def plot_polynomials(highest_degree):
x = np.arange(0,1,0.01)
for degree in np.arange(1,highest_degree+1):
coefficients = np.repeat(1,degree)
label = 'degree={}'.format(degree)
colors=plt.rcParams['axes.prop_cycle'].by_key()['color']
colors.pop(2) #Removing green from color cycle
polynomial = np.polynomial.polynomial.polyval(x, coefficients)
if degree==highest_degree:
plt.plot(x, polynomial, label=label, color='g', lw=3)
else:
plt.plot(x, polynomial, label=label, color=colors[degree-1])
plt.legend()
plt.show()
plot_polynomials(6)
输出:
注意:用 使线条变粗lw
,但这显然是可选的
编辑:从颜色循环中删除了绿色,所以只有一条绿线
推荐阅读
- html - 在右侧创建响应元素
- java - 这个 Code Pattern 的目的是什么?
- javascript - 创建 Vue 函数以更新 textarea 而无需缓冲
- python - 线程不使用python中的所有核心
- java - 如何通过 JDOM 解析 xml 文件以找到主要属性的内容
- neo4j - 在 Neo4j 中查找价格低于 3000 的机场之间的所有路径
- ramda.js - 使用 ramda 组合镜头
- python - Django,使用 ModelForm 将数据添加到外键字段的最佳方法
- reactjs - 使用 React Router 处理“覆盖页面”?
- c# - nop commerce 能否支持多个卖家