如何在绘图pandas或matplotlib python中停止折线图

Isa*_*iel 5 python matplotlib python-3.x pandas

我的挑战是绘制列中组织的许多数据序列(其中每列是同一标识符(ID)的许多模拟的数据),并且pandas数据帧的索引是模拟的月份.问题出在pandas创建的行中,链接同一列中的不同模拟.

看一下再现问题的例子.我该如何解决?

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

# create da dataset
columns = ['A','B']
data = np.array([np.random.randint(10, size=15),
             np.random.randint(10, size=15)]).T
index = list(range(0,5))*3
dataset = pd.DataFrame(data, index=index, columns=columns)

# plotting 
plot_data = dataset.plot(title='Example StackOverflow')
plot_data.set_xlabel('Years')
plot_data.set_ylabel('Values')
plot_data.legend(loc='best', ncol=4, fancybox=True, shadow=True)
plot_data.set_axis_bgcolor('w')
fig = plot_data.get_figure()
fig.savefig('example_figure_stackoverflow.png', dpi=400)
Run Code Online (Sandbox Code Playgroud)

结果

绘制结果作为链接线的问题

Ulr*_*ern 1

这里是直接使用matplotlib的解决方案:

# code until "plotting" same as question

# plotting
simlen = 5
for c in columns:
  for i in range(0, len(index), simlen):
    plt.plot(index[i:i+simlen], dataset[i:i+simlen][c],
      color=dict(A='b', B='g')[c],
      label=c if i == 0 else None)
plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

(我假设每个模拟的长度为 5,这在您的问题中并不明确。请注意,数据的结构可能有所不同,因为 pandas 不再用于绘图。)

这里的输出: 样本图