iwanttostartthecurvewithonecolorandprogressivelyblendintoanothercoloruntiltheend.thefollowingfunctioninmymymcveworks,but sus !
import numpy as np
import matplotlib.pyplot as plt
efcolorlist (颜色1,颜色2,编号) :
' ' ' generatelistofnumcolorsblendingfromcolor1to color2' ' '
wileLen(result ) num:
foriinrange (len (结果)-1 ) :
indices=NP.linspace(0,len(result )-1,num ).round (.as type (int ) ) ) ) ) ) )。
x=NP.linspace (0,2 * NP.pi,100 ) ) ) ) ) ) ) )。
y=NP.sin(x )
colors=colorlist ()、0、0 )、0、0、1 )、len )、x ) )
forIinrange(Len(x )-1 ) :
xi=x[i:i 1 1]
yi=y[i:i 1 1]
ci=colors[i]
PLT.plot(Xi,yi,color=ci,linestyle='solid ',linewidth='10 ' )
plt.show () )
notsurewhat ' better way ' refers to.asolutionwithlesscode,whichwoulddrawfasteristheuseofalinecollectiontogetherwithacolormarma
acolormapcanbedefinedbytwocolorsandanycolorsinbetweenareautomaticallyinterpolated。
cmap=matplotlib.colors.linearsegmentedcolormap.from _ list (',[ (1,0,0 ) ],) 0,0,0,1 )
alinecollectioncanbeusedtoplotalotoflinesatonce.beingascalarmappableitcanuseacolormaptocolorizeachlinedifferentlyacordingt
import numpy as np
import matplotlib.pyplot as plt
frommatplotlib.collections import特异性精灵/pfrommatplotlib.colorsimportcrdkn/px=NP.linspace (0,2 * NP.pi,100 )
y=NP.sin(x )
cmap=linearsegmentedcolormap.from _ list (',[ (1,0,0 ) ],) 0,0,1 )
points=NP.Array([x,y] ).t.reshape (-1,1,2 ) ) ) ) ) ) ) )。
segments=NP.concatenate ([ points [ :-1 ],points[1:]],axis=1) )
LC=linecollection(segments,cmap=cmap,linewidth=10 ) )。
是LC.set_Array(x )
plt.gca ().add_collection ) (LC ) )。
PLT.GCA(.Autoscale ) )。
plt.show () )
thedrawbackofthissolutionascanbeseeinthepictureisthattheindividuallinesarenotwellconnected。
So to circumvent this,onemayplotthosepointsoverlapping,using
segments=NP.concatenate ([ points [ :-2 ],points[1:-1],points[2:]],axis=1) )。
intheabovethecolorislinearlyinterpolatedbetweenthetwogivencolors.theplotthereforelooksdifferentthantheonefromthequestionuesionusionuesionuinuionconuionconusion
oobtainthesamecolorsasinthequestion, youmayusethesamefunctiontocreatethecolorsusedinthecolormapforthelinecollection.iftheaimistosimplifythisfunctionyoumaydirect lll
import numpy as np
import matplotlib.pyplot as plt
frommatplotlib.collections import特异性精灵/pfrommatplotlib.colorsimportcrdkn/px=NP.linspace (0,2 * NP.pi,100 )
y=NP.sin(x )
defcolorlist2(C1、c2、num ) :
l=NP.linspace (0,1,num ) )。
a=NP.ABS(NP.Array(C1 )-NP.array (C2 ) )
m=NP.min([C1,c2],axis=0) ) ) ) ) ) ) )。
s=NP.sign(NP.array(C2 )-NP.array (C1 ) ).as type (int ) ) ) ) ) ) 652
s[s==0]=1
cmap=linearsegmentedcolormap.from _ list (',colorlist2),0,0 ),0,0,1 ),100 ) )
points=NP.Array([x,y] ).t.reshape (-1,1,2 ) ) ) ) ) ) ) )
segments=NP.concatenate ([ points [ :-2 ],points[1:-1],points[2:]],axis=1) )。
LC=linecollection(segments,cmap=cmap,linewidth=10 ) )。
是LC.set_Array(x )
plt.gca ().add_collection ) (LC ) )。
PLT.GCA(.Autoscale ) )。
plt.show () )