gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:32:53 26 4
gpt4 key购买 nike

我的挑战是绘制列中组织的许多数据序列(其中每列是同一标识符 (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)

结果

Plot result as the problem of linking lines

最佳答案

这里是直接使用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()

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

这里输出: sample figure

关于python - 如何在 plot pandas 或 matplotlib python 中停止折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37865694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com