Python 如何使用不同的颜色绘制同一熊猫系列列的不同部分,并具有自定义索引?

Python 如何使用不同的颜色绘制同一熊猫系列列的不同部分,并具有自定义索引?,python,pandas,matplotlib,plot,Python,Pandas,Matplotlib,Plot,这是我们的后续行动 假设我有这样一个系列: testdf = pd.Series([3, 4, 2, 5, 1, 6, 10], index=['a', 'b', 'c', 'd', 'e', 'f', 'g']) 打印时,结果如下: testdf.plot() 但是,我想用蓝色(默认值)绘制前4个值的线,用红色绘制其余的线。尝试上述帖子中建议的解决方案,我得到的结果如下: fig, ax = plt.subplots(1, 1) testdf.plot(ax=ax,color='b')

这是我们的后续行动

假设我有这样一个系列:

testdf = pd.Series([3, 4, 2, 5, 1, 6, 10], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
打印时,结果如下:

testdf.plot()

但是,我想用蓝色(默认值)绘制前4个值的线,用红色绘制其余的线。尝试上述帖子中建议的解决方案,我得到的结果如下:

fig, ax = plt.subplots(1, 1)
testdf.plot(ax=ax,color='b')
testdf.iloc[3:].plot(ax=ax,color='r')

只有在不使用自定义索引定义序列时,我才能获得预期结果:

testdf = pd.Series([3, 4, 2, 5, 1, 6, 10])
fig, ax = plt.subplots(1, 1)
testdf.plot(ax=ax,color='b')
testdf.iloc[3:].plot(ax=ax,color='r')


那么,我怎样才能达到预期的效果呢?

我想写一篇评论,但是评论太长了,所以我写在这里

如果要绘制条形图(这些条形图是离散的),那么您想要实现的功能很好

在使用自定义索引时,应将序列分为两部分。一个例子是做什么

df = pd.Series([3, 4, 2, 5, 1, 6, 10], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
df1 = pd.Series(np.where(df.index<'e',df.values,np.nan), index=df.index)
df2 = pd.Series(np.where(df.index>='d',df.values,np.nan), index=df.index)
ax = df1.plot(color = 'b')
df2.plot(ax=ax,color='r')
df=pd.系列([3,4,2,5,1,6,10],索引=['a','b','c','d','e','f','g'])
df1=pd.Series(np.where(df.index='d',df.values,np.nan),index=df.index)
ax=df1。绘图(颜色='b')
df2.绘图(ax=ax,color='r')
 df = pd.Series([3, 4, 2, 5, 1, 6, 10])
 cut = 4
 ax = df[:cut].plot(color='b')
 df[(cut-1):].plot(ax=ax, color='r')
df = pd.Series([3, 4, 2, 5, 1, 6, 10], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
df1 = pd.Series(np.where(df.index<'e',df.values,np.nan), index=df.index)
df2 = pd.Series(np.where(df.index>='d',df.values,np.nan), index=df.index)
ax = df1.plot(color = 'b')
df2.plot(ax=ax,color='r')