使用不同颜色绘制线条

3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df1 = pd.DataFrame(np.random.randint(0,15,size=(15, 1)))
df2 = pd.DataFrame(np.random.randint(20,35,size=(10, 1)))


frames = [df1, df2]
result = pd.DataFrame(pd.concat(frames))

df3 = result.cumsum()
df3 = df3.reset_index(drop=False)
print(df3)
df3.plot(y=0)
plt.show()

是否可以用两种不同的颜色绘制df3线?第一种颜色用于行0到14,第二种颜色用于行15到24。我想标记df1结束和df2开始的位置。

2个回答

1
什么意思。
#[...]
df3 = result.cumsum()
df3 = df3.reset_index(drop=False)
plt.plot(df3.mask(df3.apply(lambda x: x.index < 15))[0], color='blue')
plt.plot(df3.mask(df3.apply(lambda x: x.index > 15))[0], color='green')
plt.show()
plt.close()# do not forget this to save you from Runtime Error.

enter image description here


1

只需绘制数据框中您想要的部分,以任何您喜欢的颜色,例如df3.iloc[:15,:].plot(color="green")

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df1 = pd.DataFrame(np.random.randint(0,15,size=(15, 1)))
df2 = pd.DataFrame(np.random.randint(20,35,size=(10, 1)))


frames = [df1, df2]
result = pd.DataFrame(pd.concat(frames))

df3 = result.cumsum()
df3 = df3.reset_index(drop=False)
print(df3)
ax = df3.iloc[:15,:].plot(y=0, color="crimson")
df3.iloc[15:,:].plot(y=0, color="C0", ax=ax)
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接